Data Structures With Python - 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

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)
d1.day()
d1.month()
d1.year()

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


Data Structures with Python 20CS41P

d1.monthName()
d1.isLeapYear()

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

import time
class stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
def display(self):
return (self.items)
s=stack()
start = time.time()
print(s.isEmpty())
print("push operations")
s.push(11)
s.push(12)
s.push(13)
print("size:",s.size())
print(s.display())
print("peek",s.peek())
print("pop operations")
print(s.pop())
print(s.pop())
print(s.display())
print("size:",s.size())
end = time.time()
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 = time.time()
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 = time.time()
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 = time.time()
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 = time.time()
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):
f.append(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):
self.data = data
self.next = None

class SinglyLinkedList:
def __init__(self):
self.first = None

def insertFirst(self, data):


temp = Node(data)
if(self.first == None):
self.first=temp
else:
temp.next=self.first
self.first=temp

def removeFirst(self):
if(self.first== None):
print("list is empty")
else:
cur=self.first
self.first=self.first.next
print("the deleted item is",cur.data)

def display(self):
if(self.first== None):
print("list is empty")
return
current = self.first
while(current):
print(current.data, end = " ")
current = current.next

def search(self,item):
if(self.first== None):
print("list is empty")
return
current = self.first
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 current.data == item:
found = True
else:
current = current.next
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:")
ll.insertFirst(item)
ll.display()
elif(c1 == 2):
ll.removeFirst()
ll.display()
elif(c1 == 3):
item = input("Enter the element to search:")
ll.search(item)
elif(c1 == 4):
ll.display()
else:
break

12. Implement singly linked list using Iterators.

class Node:
def __init__(self, data = None):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.first = None

def insert(self, data):


temp = Node(data)
if(self.first):
current = self.first
while(current.next):
current = current.next
current.next = temp
else:
self.first = temp

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


Data Structures with Python 20CS41P

def __iter__(self):
current = self.first
while current:
yield current.data
current = current.next

# Linked List Iterators


ll = LinkedList()
ll.insert(9)
ll.insert(98)
ll.insert("welcome")
ll.insert("govt polytechnic koppal")
ll.insert(456.35)
ll.insert(545)
ll.insert(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:")
s.append(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 ["(", "{", "["]:
stack.append(char)
else:
if not stack:
return False
current_char = stack.pop()
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:")
q.append(item)
def dequeue():
if not q:
print("Queue is Empty")
else:
item=q.pop(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("1.Insert 2.Delete 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):
self.item = item
self.priority = priority
class PriorityQueue:
def __init__(self):
self.qList = list()
def isEmpty(self):
return len(self) == 0
def __len__(self):
return len(self.qList)
def enqueue(self, item, priority):
entry = PriorityQEntry(item, priority)
if self.__len__() == 0:
self.qList.append(entry)
else:
for x in range(0, len(self)):
if entry.priority >= self.qList[x].priority:
if x == (len(self)- 1):
self.qList.insert(x + 1, entry)
else:
continue
else:
self.qList.insert(x, entry)
return True
def dequeue(self):
assert not self.isEmpty(), "Cannot dequeue from an empty queue."
return self.qList.pop(0)
def display(self):
Dept. of Computer Science and Engg. Page 11 Govt. Polytechnic Koppal
Data Structures with Python 20CS41P

for x in self.qList:
print (str(x.item)+"-"+str(x.priority))

q=PriorityQueue()
print("Enque")
q.enqueue(25,3)
q.enqueue(50,2)
q.enqueue(75,1)
q.enqueue(100,6)
q.display()
print("Deque")
q.dequeue()
q.dequeue()
q.display()

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

You might also like