100% found this document useful (1 vote)
1K views12 pages

Data Structures with Python Lab Manual

The document discusses implementation of various data structures and algorithms in Python. It includes implementations of lists, dictionaries, tuples, sets, date class as an ADT, stack class with operations, linear search, bubble sort, selection sort, insertion sort, binary search recursively and iteratively, Fibonacci sequence with dynamic programming, singly linked list with operations, linked list using iterators, and stack operations. Space and time complexities are analyzed for many algorithms.

Uploaded by

Vikas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views12 pages

Data Structures with Python Lab Manual

The document discusses implementation of various data structures and algorithms in Python. It includes implementations of lists, dictionaries, tuples, sets, date class as an ADT, stack class with operations, linear search, bubble sort, selection sort, insertion sort, binary search recursively and iteratively, Fibonacci sequence with dynamic programming, singly linked list with operations, linked list using iterators, and stack operations. Space and time complexities are analyzed for many algorithms.

Uploaded by

Vikas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Data Structures with Python 20CS41P

1. Python program to Use and demonstrate basic data structures.

print("List")
l1 = [1, 2,"ABC", 3, "xyz", 2.3]
print(l1)
print("Dictionary")
d1={"a":134,"b":266,"c":343}
print(d1)
print("Tuples")
t1=(10,20,30,40,50,40)
print (t1)
print("Sets")
s1={10,30,20,40,10,30,40,20,50,50}
print(s1)

2. Implement an ADT with all its operations.

class date:
def __init__(self,a,b,c):
self.d=a
self.m=b
self.y=c
def day(self):
print("Day = ", self.d)
def month(self):
print("Month = ", self.m)
def year(self):
print("year = ", self.y)
def monthName(self):
months = ["Unknown","January","Febuary","March","April","May","June","July",
"August","September","October","November","December"]
print("Month Name:",months[self.m])
def isLeapYear(self):
if (self.y % 400 == 0) and (self.y % 100 == 0):
print("It is a Leap year")
elif (self.y % 4 == 0) and (self.y % 100 != 0):
print("It is a Leap year")
else:
print("It is not a Leap year")
d1 = date(3,8,2000)
[Link]()
[Link]()
[Link]()

Dept. of Computer Science and Engg. Page 1 Govt. Polytechnic Koppal


Data Structures with Python 20CS41P

[Link]()
[Link]()

3. Implement an ADT and Compute space and time complexities.

import time
class stack:
def __init__(self):
[Link] = []
def isEmpty(self):
return [Link] == []
def push(self, item):
[Link](item)
def pop(self):
return [Link]()
def peek(self):
return [Link][len([Link]) - 1]
def size(self):
return len([Link])
def display(self):
return ([Link])
s=stack()
start = [Link]()
print([Link]())
print("push operations")
[Link](11)
[Link](12)
[Link](13)
print("size:",[Link]())
print([Link]())
print("peek",[Link]())
print("pop operations")
print([Link]())
print([Link]())
print([Link]())
print("size:",[Link]())
end = [Link]()
print("Runtime of the program is", end - start)

Dept. of Computer Science and Engg. Page 2 Govt. Polytechnic Koppal


Data Structures with Python 20CS41P

4. Implement Linear Search and compute space and time complexities, plot graph using asymptomatic
notations

import time
def linearsearch(a, key):
n = len(a)
for i in range(n):
if a[i] == key:
return i;
return -1
a = [13,24,35,46,57,68,79]
start = [Link]()
print("the array elements are:",a)
k = int(input("enter the key element to search:"))
i = linearsearch(a,k)
if i == -1:
print("Search UnSuccessful")
else:
print("Search Successful key found at location:",i+1)
end = [Link]()
print("Runtime of the program is", end-start)

5. Implement Bubble Sort and compute space and time complexities, plot graph using asymptomatic
notations

def bubblesort(a):
n = len(a)
for i in range(n-2):
for j in range(n-2-i):
if a[j]>a[j+1]:
temp = a[j]
a[j] = a[j+1]
a[j+1] = temp
x = [34,46,43,27,57,41,45,21,70]
print("Before sorting:",x)
bubblesort(x)
print("After sorting:",x)

6. Implement Selection Sort and compute space and time complexities, plot graph using asymptomatic
notations

def selectionsort(a):
n = len(a)
Dept. of Computer Science and Engg. Page 3 Govt. Polytechnic Koppal
Data Structures with Python 20CS41P

for i in range(n-2):
min = i
for j in range(i+1,n-1):
if a[j]<a[min]:
min=j
temp = a[i]
a[i] = a[min]
a[min] = temp
x = [34,46,43,27,57,41,45,21,70]
print("Before sorting:",x)
selectionsort(x)
print("After sorting:",x)

7. Implement Insertion Sort and compute space and time complexities, plot graph using asymptomatic
notations

def insertionsort(a):
n = len(a)
for i in range(1,n-1):
v=a[i]
j = i-1
while j>=0 and a[j]>v:
a[j+1] = a[j]
j=j-1
a[j+1] = v
x = [34,46,43,27,57,41,45,21,70]
print("Before sorting:",x)
insertionsort(x)
print("After sorting:",x)

8. Implement Binary Search and compute space and time complexities, plot graph using asymptomatic
notations

import time
def binarysearch(a, key):
low = 0
high = len(a) - 1
while low <= high:
mid = (high + low) // 2
if a[mid] == key:
return mid
elif key < a[mid]:
high = mid - 1
Dept. of Computer Science and Engg. Page 4 Govt. Polytechnic Koppal
Data Structures with Python 20CS41P

else :
low = mid + 1
return -1
start = [Link]()
a = [13,24,35,46,57,68,79]
print("the array elements are:",a)
k = int(input("enter the key element to search:"))
r = binarysearch(a,k)
if r == -1:
print("Search UnSuccessful")
else:
print("Search Successful key found at location:",r+1)
end = [Link]()
print("Runtime of the program is:", end-start)

9. Implement Binary Search using Recursion and compute space and time complexities, plot graph
using asymptomatic notations

def binarysearch(a, low, high, key):


if low <= high:
mid = (high + low) // 2
if a[mid] == key:
print("Search Successful key found at location:",mid+1)
return
elif key < a[mid]:
binarysearch(a, low, mid-1, k)
else :
binarysearch(a, mid + 1, high, k)
else:
print("Search UnSuccessful")
a = [13,24,35,46,57,68,79]
print("the array elements are:",a)
k = int(input("enter the key element to search:"))
binarysearch(a, 0, len(a)-1, k)

10. Implement Fibonacci sequence with dynamic programming.

def fib(n):
if n<=1:
return n
f = [0, 1]
for i in range(2, n+1):
[Link](f[i-1] + f[i-2])
print("The Fibonacci sequence is:",f)

Dept. of Computer Science and Engg. Page 5 Govt. Polytechnic Koppal


Data Structures with Python 20CS41P

return f[n]
n=int(input("Enter the term:"))
print("The Fibonacci value is:",fib(n))

11. Implement singly linked list (Traversing the Nodes, searching for a Node, Prepending Nodes, and
Removing Nodes)

class Node:
def __init__(self, data = None):
[Link] = data
[Link] = None

class SinglyLinkedList:
def __init__(self):
[Link] = None

def insertFirst(self, data):


temp = Node(data)
if([Link] == None):
[Link]=temp
else:
[Link]=[Link]
[Link]=temp

def removeFirst(self):
if([Link]== None):
print("list is empty")
else:
cur=[Link]
[Link]=[Link]
print("the deleted item is",[Link])

def display(self):
if([Link]== None):
print("list is empty")
return
current = [Link]
while(current):
print([Link], end = " ")
current = [Link]

def search(self,item):
if([Link]== None):
print("list is empty")
return
current = [Link]
found = False
while current != None and not found:
Dept. of Computer Science and Engg. Page 6 Govt. Polytechnic Koppal
Data Structures with Python 20CS41P

if [Link] == item:
found = True
else:
current = [Link]
if(found):
print("Item is present in the linked list")
else:
print("Item is not present in the linked list")

#Singly Linked List


ll = SinglyLinkedList()
while(True):
c1 = int(input("\nEnter your choice 1-insert 2-delete 3-search 4-display 5-exit :"))
if(c1 == 1):
item = input("Enter the element to insert:")
[Link](item)
[Link]()
elif(c1 == 2):
[Link]()
[Link]()
elif(c1 == 3):
item = input("Enter the element to search:")
[Link](item)
elif(c1 == 4):
[Link]()
else:
break

12. Implement singly linked list using Iterators.

class Node:
def __init__(self, data = None):
[Link] = data
[Link] = None

class LinkedList:
def __init__(self):
[Link] = None

def insert(self, data):


temp = Node(data)
if([Link]):
current = [Link]
while([Link]):
current = [Link]
[Link] = temp
else:
[Link] = temp

Dept. of Computer Science and Engg. Page 7 Govt. Polytechnic Koppal


Data Structures with Python 20CS41P

def __iter__(self):
current = [Link]
while current:
yield [Link]
current = [Link]

# Linked List Iterators


ll = LinkedList()
[Link](9)
[Link](98)
[Link]("welcome")
[Link]("govt polytechnic koppal")
[Link](456.35)
[Link](545)
[Link](5)
for x in ll:
print(x)

13. Implement Stack Data Structure.

s = []
def push():
if len(s) == size:
print("Stack is Full")
else:
item = input("Enter the element:")
[Link](item)
def pop():
if(len(s) == 0):
print("Stack is Empty")
else:
item = s[-1]
del(s[-1])
print("The deleted element is:",item)
def display():
size = len(s)
if(size== 0):
print("Stack is Empty")
else:
for i in reversed(s):
print(i)
size=int(input("Enter the size of Stack:"))
while(True):
choice = int(input("1-Push 2-POP 3-DISPLAY 4-EXIT Enter your choice:"))
if(choice == 1):

Dept. of Computer Science and Engg. Page 8 Govt. Polytechnic Koppal


Data Structures with Python 20CS41P

push()
elif(choice == 2):
pop()
elif(choice == 3):
display()
else:
break

14. Implement bracket matching using stack.

def bracketmatching(expr):
stack = []
for char in expr:
if char in ["(", "{", "["]:
[Link](char)
else:
if not stack:
return False
current_char = [Link]()
if current_char == '(':
if char != ")":
return False
if current_char == '{':
if char != "}":
return False
if current_char == '[':
if char != "]":
return False
if stack:
return False
return True
expr = "{()}[]"
if bracketmatching(expr):
print("Matching")
else:
print("Not Matching")

15. Program to demonstrate recursive operations (factorial/ Fibonacci)


a) Factorial

def fact(n):
if n == 1:
return 1
else:
return (n * fact(n-1))
n=int(input("Enter the number:"))

Dept. of Computer Science and Engg. Page 9 Govt. Polytechnic Koppal


Data Structures with Python 20CS41P

print("The factorial of a number is:",fact(n))

b) Fibonacci

def fib(n):
if n<=1:
return n
return fib(n-1) + fib(n-2)
n=int(input("Enter the range:"))
print("The fibonacci value is:",fib(n))

16. Implement solution for Towers of Hanoi.

def towerofhanoi(n, source, destination, auxiliary):


if n==1:
print ("Move disk 1 from source",source,"to destination",destination)
return
towerofhanoi(n-1, source, auxiliary, destination)
print ("Move disk",n,"from source",source,"to destination",destination)
towerofhanoi(n-1, auxiliary, destination, source)
n=4
towerofhanoi(n,'A','B','C')

17. Implement Queue Data Structure.

q=[]
def enqueue():
if len(q)==size:
print("Queue is Full")
else:
item=input("Enter the element:")
[Link](item)
def dequeue():
if not q:
print("Queue is Empty")
else:
item=[Link](0)
print("Element removed is:",item)
def display():
if not q:# or if len(q) == 0
print("Queue is Empty")
else:
print(q)
Dept. of Computer Science and Engg. Page 10 Govt. Polytechnic Koppal
Data Structures with Python 20CS41P

size=int(input("Enter the size of Queue:"))


while True:
choice=int(input("[Link] [Link] 3. Display 4. Quit Enter your choice:"))
if choice==1:
enqueue()
elif choice==2:
dequeue ()
elif choice==3:
display()
else:
break

18. Implement Priority Queue Data Structure.

class PriorityQEntry(object):
def __init__(self, item, priority):
[Link] = item
[Link] = priority
class PriorityQueue:
def __init__(self):
[Link] = list()
def isEmpty(self):
return len(self) == 0
def __len__(self):
return len([Link])
def enqueue(self, item, priority):
entry = PriorityQEntry(item, priority)
if self.__len__() == 0:
[Link](entry)
else:
for x in range(0, len(self)):
if [Link] >= [Link][x].priority:
if x == (len(self)- 1):
[Link](x + 1, entry)
else:
continue
else:
[Link](x, entry)
return True
def dequeue(self):
assert not [Link](), "Cannot dequeue from an empty queue."
return [Link](0)
def display(self):
Dept. of Computer Science and Engg. Page 11 Govt. Polytechnic Koppal
Data Structures with Python 20CS41P

for x in [Link]:
print (str([Link])+"-"+str([Link]))

q=PriorityQueue()
print("Enque")
[Link](25,3)
[Link](50,2)
[Link](75,1)
[Link](100,6)
[Link]()
print("Deque")
[Link]()
[Link]()
[Link]()

Dept. of Computer Science and Engg. Page 12 Govt. Polytechnic Koppal

Common questions

Powered by AI

Asymptotic notations like Big O, Θ, and Ω are crucial in analyzing algorithm performance because they provide a high-level classification of an algorithm's efficiency without mechanical or platform constraints. For instance, for search algorithms like Linear and Binary Search, asymptotic notations help in understanding best, average, and worst-case scenarios. Linear Search has a time complexity of O(n) as it involves checking each element sequentially . In contrast, Binary Search has a time complexity of O(log n) because it divides the array into halves, significantly reducing the number of comparisons . For sorting algorithms, these notations help compare theoretical efficiency limits, such as Bubble Sort's O(n^2) versus more advanced algorithms like Merge Sort's O(n log n) (although Merge Sort is not covered in the document). Asymptotic notations are therefore vital for predicting and comparing performances theoretically independent of specific implementation details or hardware. .

The Tower of Hanoi is a classic problem involving three rods and a number of disks of different sizes. The goal is to move the entire stack of disks to another rod, following rules of moving only one disk at a time, placing only smaller disks on larger ones . The recursive solution involves moving n-1 disks from source to auxiliary using destination, then moving the nth disk to destination, and finally moving n-1 disks from auxiliary to destination using source. This divide-and-conquer strategy, implemented as towerofhanoi(n, source, destination, auxiliary), recursively resolves smaller subproblems, demonstrating the powerful use of recursion in problem-solving .

To implement an ADT in Python, such as a 'date' class, a variety of operations can be defined that manage the attributes of an object. The class can encapsulate attributes like day, month, and year, and offer methods to access these attributes. The example with class date defines operations such as day(), month(), year(), monthName(), and isLeapYear() that interact with the attributes to extract or compute necessary data . For example, the monthName() function translates a month number into its corresponding name, and isLeapYear() checks if a year is a leap year using the rules of the Gregorian calendar .

Recursive algorithms solve a problem by calling themselves with a subproblem. This concept applies to calculating factorials, where fact(n) returns n * fact(n-1) until n equals 1 . The recursive calculation of Fibonacci sequences operates similarly, where fib(n) = fib(n-1) + fib(n-2) continues until the base case n <= 1 . These implementations demonstrate how recursive solutions break down problems into smaller, more manageable parts, making them intuitive for operations involving sequences or hierarchical computations .

Python allows for easy manipulation of basic data structures such as lists, dictionaries, tuples, and sets. For example, a list can contain various data types and is mutable as shown with l1 = [1, 2, "ABC", 3, "xyz", 2.3] which adds multiple data types . A dictionary stores key-value pairs, exemplified with d1 = {"a": 134, "b": 266, "c": 343} . Tuples, such as t1 = (10, 20, 30, 40, 50, 40), are immutable and ordered collections . Sets, like s1 = {10, 30, 20, 40, 50}, automatically remove duplicates and store unordered collections of unique items .

In Python, a priority queue can be implemented using a wrapper class, such as PriorityQEntry, to keep items with associated priorities and a list to maintain the queue . Unlike a regular queue that serves the elements by order of insertion, a priority queue serves elements based on their priority. The enqueue(item, priority) operation inserts elements into the list according to their priority, using insertion sort techniques to maintain the list order, while the dequeue() operation removes the element with the highest priority (highest priority level denotes the peak position in the queue). This feature is essential for processes that require scheduling based on importance, rather than order of arrival .

The binary search algorithm is implemented by iteratively or recursively dividing the search interval in half. If the midpoint of the array is the target value, the search ends; otherwise, the interval is narrowed to the half that may contain the target . For its optimal performance, the array must be sorted. The key condition is that each iteration (or recursion) reduces the problem size by a factor of two, which ensures a time complexity of O(log n). However, its efficiency is contingent upon the sorted nature of the array, distinguishing it from other search algorithms which may not have this requirement .

A stack in Python can be implemented using a list where operations like push and pop follow Last In First Out (LIFO) protocol. Typical operations include isEmpty() to check if the stack is empty, push(item) to add an item, pop() to remove the most recently added item, peek() to view the top item without removing it, size() to get the number of items, and display() to print all elements . The implementation of the stack class in Python provided uses a list to maintain stack operations, illustrating each function's definition and how they interact with the data structure .

In Python, a queue can be implemented using a list with operations that follow the First In First Out (FIFO) principle. Fundamental operations include enqueue(item) to add an element at the end of the queue and dequeue() to remove the first element . Additional operations are isEmpty() to check if the queue is empty and display() to print the elements. The implementation of queues improves the efficient handling of dynamical data, such as waitlists and scheduling problems, characterized by these operations .

Bubble Sort, Selection Sort, and Insertion Sort can be compared based on their time and space complexities. Bubble Sort has a time complexity of O(n^2) because it repeatedly passes through the list, compares adjacent elements, and swaps them if they are in the wrong order . Selection Sort also has a time complexity of O(n^2), as it selects the smallest element from the unsorted portion and places it at the beginning, iterating over the list multiple times . Insertion Sort has a similar average and worst-case time complexity of O(n^2) but is more efficient when the list is partially sorted, as it builds the sorted array one item at a time . The space complexity for all three sorts is O(1) because they are in-place sorting algorithms .

Data Structures with Python                                                                              20CS41P 
 
Dept. of
Data Structures with Python                                                                              20CS41P 
 
Dept. of
Data Structures with Python                                                                              20CS41P 
 
Dept. of
Data Structures with Python                                                                              20CS41P 
 
Dept. of
Data Structures with Python                                                                              20CS41P 
 
Dept. of
Data Structures with Python                                                                              20CS41P 
 
Dept. of
Data Structures with Python                                                                              20CS41P 
 
Dept. of
Data Structures with Python                                                                              20CS41P 
 
Dept. of
Data Structures with Python                                                                              20CS41P 
 
Dept. of
Data Structures with Python                                                                              20CS41P 
 
Dept. of

You might also like