Data Structures With Python - 1
Data Structures With Python - 1
Data Structures With Python - 1
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)
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()
d1.monthName()
d1.isLeapYear()
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)
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 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)
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 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")
class Node:
def __init__(self, data = None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.first = None
def __iter__(self):
current = self.first
while current:
yield current.data
current = current.next
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):
push()
elif(choice == 2):
pop()
elif(choice == 3):
display()
else:
break
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")
def fact(n):
if n == 1:
return 1
else:
return (n * fact(n-1))
n=int(input("Enter the number:"))
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))
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
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()