Data Structures Through Python Lab Record 23-24-IISEM
Data Structures Through Python Lab Record 23-24-IISEM
Week – 1
PROGRAM- 1
Write a Python program to
a) Compute the GCD of two numbers
b) Display first “N” prime numbers
c) Display first “N” Fibonacci sequence
d) Find the factorial value of a given number
PROGRAM – 1a:
ALGORITHM:
1. Start
2. Create a definition with def gcd(a,b):
if(b==0): return a
else: return gcd(b,a%b)
3. Read first number into a
4. Read second number into b
5. Call the function using gcd(a,b)
6. Print the result
7. Stop
SOURCE CODE:
#compute the GCD of two numbers
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
num1=int(input("Enter number1:"))
num2=int(input("Enter number2:"))
res=gcd(num1,num2)
print("GCD of",num1,"and",num2,"is",res)
#print(f"GCD of {num1} and {num2} is {res}")
'''
import math
num1=int(input("Enter number1:"))
num2=int(input("Enter number2:"))
print(f"GCD of {num1} and {num2} is {math.gcd(num1,num2)}")
'''
OUTPUT
PROGRAM – 1b:
ALGORITHM:
1. Start
2. Read the number N from user
3. Initialize count=0
4. Run for loop i from 1-n
5. Run for loop j within i loop from 1-i
6. Increment count with condition if i%j=0
7. If count=2 display i and set back count=0 and continue
8. Stop
SOURCE CODE:
n=int(input("Enter n:"))
count=0
i=2
for i in range(2,n+1):
count=0
for j in range(1,i+1):
if(i%j==0):
count+=1
if(count==2):
print(i)
OUTPUT
PROGRAM – 1c:
ALGORITHM:
1. Start
2. Initialize a=0, b=1, c=0
3. Read the number of terms needed from user and store it in n
4. Print a and b values
5. Run the loop for n-2 times and write the following code:
while(n-2):
c=a+b
a=b
b=c
print(c,end=" ")
n=n-1
6. End
SOURCE CODE:
n=int(input("Enter n value"))
f1=0
f2=1
print(f"{f1}\n{f2}")
for i in range(3,n+1):
f3=f1+f2
f1=f2
f2=f3
print(f3)
OUTPUT
PROGRAM – 1d:
ALGORITHM:
1. Start
2. Read the number from user and store it to n
3. Initialize variable fact=1
4. Write the following code:
While (n>0):
fact = fact*n
n=n-1
5. Print the result which is available in fact
6. Stop
SOURCE CODE:
n=int(input("Enter n:"))
fact=1
for i in range(1,n+1):
fact*=i
print(f"Factorial of {n} is {fact}")
'''
import math
n=int(input("Enter n:"))
print(f"Factorial of {n} is {math.factorial(n)}")
'''
OUTPUT
VIVA - VOCE
Arithmetic operators.
Assignment operators.
Comparison operators.
Logical operators.
Identity operators.
Membership operators.
Bitwise operators.
Applications Python are Web and Internet Development, Scientific and Numeric, Education,
Desktop GUIs, Software Development, Business Applications.
Week – 2
PROGRAM-2
Write a Python program
a) Check whether the given string is palindrome or not.
b) Simulate simple Calculator.
c) Count the characters in the string and store them in a dictionary data structure.
d) Find the most frequent words in a text.
PROGRAM – 2 a:
AIM: Python program to check whether the given string is palindrome or not.
ALGORITHM:
1. Start
2. Read input text from user and store it in a variable named string
3. Write the following code:
if (string==string[::-1]):
print ("The string is a palindrome");
else:
print ("The string isn't a palindrome");
4. End
SOURCE CODE:
#check whether the given string is palindrome or not
s=input("Enter string:")
s1=s[::-1]
if(s==s1):
print(f"{s} is palindrome")
else:
print(f"{s} is not palindrome")
OUTPUT:
PROGRAM – 2 b:
ALGORITHM:
1. Start
2. Read num1, num2 from user
3. Display menu of various arithmetic operations on numbers
4. Read choice from user
5. Perform the operation opted by user
6. Print the result
7. Stop
SOURCE CODE:
OUTPUT
PROGRAM – 2 c:
AIM: Python program to count the characters in the string and store them in a dictionary data
structure.
ALGORITHM:
1. Start
2. Read input text from user and store it in str1
3. Initialize the dictionary using dict = {}
4. Write the following code:
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
5. Print the resultant dictionary
6. Stop
SOURCE CODE:
#count the characters in the string and store them in a dictionary data structure
str1=input()
dict1={}
for i in str1:
keys=dict1.keys()
if i in keys:
dict1[i]+=1
else:
dict1[i]=1
print(dict1)
OUTPUT
PROGRAM – 2 d:
ALGORITHM:
1. Start
2. Open a file in read mode
3. Initialize maxCount=0 and word=""
4. Get each line till end of file is reached
5. Split each line into words using the split() method
6. Append all the words to a list
7. Determine the most repeated word in the list
8. Count the frequency of each word in the list and store it in a variable named count
9. If maxCount is less than count then store value of count into maxCount and the corresponding word
to the variable named word
10. Stop
SOURCE CODE:
#find the most frequent words in a text
file=input("enter file name")
f=open(file)
str1=f.read().strip()
str2=str1.split()
dict1={}
k=dict1.keys()
for n in str2:
if n in k:
dict1[n]+=1
else:
dict1[n]=1
max1=max(dict1.values())
print(f"below word(s) repeated {max1} times")
for key,value in dict1.items():
if value==max1:
print(key)
OUTPUT
VIVA - VOCE
2. What is the difference between string comparison and string ‘n’ comparison?
Week – 3
PROGRAM - 3:
Write a Python program to perform
a) Linear Search.
b) Binary Search.
PROGRAM – 3 a:
AIM: Python program to perform Linear Search.
ALGORITHM:
1. Start
2. Read the list of numbers in a variable named alist
3. Perform the split operation on the list using alist = alist.split()
4. alist = [int(x) for x in alist]
5. Read the number to search for to variable named key
6. Write the following code:
index = linear_search(alist, key)
if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))
7. Stop
SOURCE CODE:
def linear_search(a,key):
for i in range(len(a)):
if(a[i]==key):
return i
return -1
OUTPUT
PROGRAM – 3 b
AIM: Python program to perform Binary Search.
ALGORITHM:
1. Start
2. Read the sorted list of numbers in a variable named alist
3. Perform the split operation on the list using alist = alist.split()
4. alist = [int(x) for x in alist]
5. Read the number to search for to variable named key
6. Write the following code:
index = binary_search(alist, key)
if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))
7. Stop
SOURCE CODE:
def binary_search(a,key):
start=0
end=len(a)
while(start<end):
mid=(start+end)//2
if(a[mid]>key):
end=mid
elif(a[mid]<key):
start=mid+1
else:
return mid
return -1
OUTPUT
VIVA - VOCE
Searching is the process of finding a given value position in a list of values. It decides
whether a search key is present in the data or not.
The drawback of a linear search is the fact that its time consuming for the enormous
arrays.
Inversely, slow searching of big lists.
3. During linear search, when the record is present in first position then how many
comparisons are made?
Week – 4
PROGRAM - 4:
a) Write a Python program to compute the matrix multiplication.
b) Write a Python program to find mean, median, mode for the given set of numbers in alist.
c) Write 2 functions dups to find all duplicates and unique to find all unique elements ofa list.
PROGRAM – 4 a
AIM: C Python program to compute the matrix multiplication.
ALGORITHM:
1. Start
2. Read matrix1 with order m1*n1
3. Read matrix2 with order m2*n2
4. Check if n1=m2 or not
5. If n1!=m2 display that matrix multiplication is not possible
6. If n1=m2 perform multiplication of two matrixes
7. Print the resultant matrix
8. Stop
SOURCE CODE:
#compute the matrix multiplication
m1=int(input("Enter no.of rows in Matrix1:"))
n1=int(input("Enter no.of columns in Matrix1:"))
m2=int(input("Enter no.of rows in Matrix2:"))
n2=int(input("Enter no.of columns in Matrix2:"))
if(n1!=m2):
print("Matrix multiplication is not possible")
else:
a=[[0 for j in range(n1)]for i in range(m1)]
b=[[0 for j in range(n2)]for i in range(m2)]
c=[[0 for j in range(n2)]for i in range(m1)]
print("Enter elemnets fro Matrix1:")
for i in range(m1):
for j in range(n1):
a[i][j]=int(input())
print("Enter elemnets fro Matrix12:")
for i in range(m2):
for j in range(n2):
b[i][j]=int(input())
print("Resultant Matrix:")
for i in range(m1):
for j in range(n2):
for k in range(m2):
c[i][j]+=a[i][k]*b[k][j]
print(c)
OUTPUT:
SOURCE CODE 2:
a=[]
b=[]
c=[]
r1=int(input("Enter r1 value"))
c1=int(input("Enter c1 value"))
r2=int(input("Enter r2 value"))
c2=int(input("Enter c2 value"))
if(r1==c2):
print("Enter elements into b matrix")
for i in range(r1):
a.append([])
for j in range(c1):
a[i].append(int(input()))
print(" a matrix is")
for i in range(r1):
for j in range(c1):
print(a[i][j],end=" ")
print("\n")
print("Enter elements into b matrix")
for i in range(r2):
b.append([])
for j in range(c2):
b[i].append(int(input()))
print(" b matrix is")
for i in range(r2):
for j in range(c2):
B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 22
CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT
print(b[i][j],end=" ")
print("\n")
for i in range(r1):
c.append([])
for j in range(c2):
c[i].append(0)
for i in range(r1):
for j in range(c2):
c[i][j]=0
for k in range(r2):
c[i][j]+=a[i][k]*b[k][j]
print(" c matrix is")
for i in range(r1):
for j in range(c2):
print(c[i][j],end=" ")
print("\n")
OUTPUT:
PROGRAM – 4 b
AIM: Python program to find mean, median, mode for the given set of numbers in a list.
ALGORITHM:
1. Start
2. n_num = [1, 2, 3, 4, 5, 5]
3. n = len(n_num)
4. get_sum = sum(n_num)
5. mean = get_sum / n
6. print("Mean or Average is: " + str(mean))
7. if n % 2 == 0:
8. median1 = n_num[n//2]
9. median2 = n_num[n//2 - 1]
10. median = (median1 + median2)/2
11. else:
12. median = n_num[n//2]
13. print("Median is: " + str(median))
14. data = Counter(n_num)
15. get_mode = dict(data)
16. mode = [k for k, v in get_mode.items() if v == max(list(data.values()))]
17. if len(mode) == n:
18. get_mode = "No mode found"
19. else:
20. get_mode = "Mode is: " + ', '.join(map(str, mode))
21. print(get_mode)
22. Stop
SOURCE CODE:
#find mean, median, mode for the given set of numbers in a list
a=list(map(int,input("Enter space seperated list of numbers:").split()))
print("Mean=",sum(a)/len(a))
a.sort()
if(len(a)%2==1):
print("Median=",a[len(a)//2])
else:
print("Median=",(a[len(a)//2-1]+a[len(a)//2])/2)
dict1={}
for i in a:
keys=dict1.keys()
if i in keys:
dict1[i]+=1
else:
B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 24
CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT
dict1[i]=1
max1=max(dict1.values())
mode=[]
for i in dict1:
if(dict1[i]==max1):
mode.append(i)
print("Mode=",mode)
OUTPUT
l=[]
n=int(input("Enter n value"))
print(f"Enter {n} elements into list")
for i in range(n):
ele=int(input())
l.append(ele)
print(l)
mean=sum(l)//len(l)
print("mean:",mean)
l.sort()
if(len(l)%2==1):
print("Median=",l[len(l)//2])
else:
print("Median=",(l[len(l)//2-1]+l[len(l)//2])/2)
c=[]
s=set()
for i in l:
c.append(l.count(i))
for i in l:
if(max(c)==l.count(i)):
B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 25
CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT
s.add(i)
print("Mode=",list(s))
OUTPUT:
PROGRAM – 4(C)
AIM: Python program for 2 functions dups to find all duplicates and unique to find all unique elements
of a list.
ALGORITHM:
1. Start
2. def dups(x):
3. size = len(x)
4. repeated = []
5. for i in range(size):
6. k=i+1
7. for j in range(k, size):
8. if x[i] == x[j] and x[i] not in repeated:
9. repeated.append(x[i])
10. return repeated
11. def unique(x):
12. size = len(x)
13. unique = []
14. for i in range(size):
15. k=i+1
16. for j in range(k, size):
17. if x[i] != x[j] and x[i] not in unique:
18. unique.append(x[i])
19. return unique
20. list1 = Input list
21. print(dups(list1))
22. print(unique(list1))
23. End
SOURCE CODE:
#create 2 functions dups and unique to find all duplicate and unique elements of a list
a=list(map(int,input("Enter space seperated list of numbers:").split()))
dict1={}
for i in a:
keys=dict1.keys()
if i in keys:
dict1[i]+=1
else:
dict1[i]=1
def dups(dict1):
dups=[]
for i in dict1:
if(dict1[i]>1):
dups.append(i)
print("Duplicate values are:",dups)
def unique(dict1):
uniq=[]
for i in dict1:
if(dict1[i]==1):
uniq.append(i)
print("Unique values are:",uniq)
dups(dict1)
unique(dict1)
OUTPUT:
VIVA – VOCE
The difference between the two methods is that . append() adds an item to the end of a list,
whereas . insert() inserts and item in a specified position in the list
5. Give your idea to find duplicate and unique elements in a list of integer
The idea is to use nested loop and for each element check if the element is present in the array more
than once or not.
Week -5
PROGRAM - 5:
a) Write a Python function to compute “N”/0 and use try/except to catch the exceptions.
b) Write a program to define a custom exception class which takes a string message as attribute.
PROGRAM – 5 a:
AIM: Python function to compute “N”/0 and use try/except to catch the exceptions.
ALGORITHM:
1. Start
2. Read a number into a variable named N
3. Compute result = N/0
4. print("Result: ", result)
5. except ZeroDivisionError:
6. print("Exception Handler for ZeroDivisionError")
7. print("We cannot divide a number by 0")
8. Stop
SOURCE CODE:
#compute “N”/0 and use try/except to catch the exceptions
try:
n1=int(input("Enter dividend:"))
n2=int(input("Enter divisor:"))
print("Quotient:",n1/n2)
except ZeroDivisionError:
print("We cannot divide a number by 0")
except ValueError:
print("Enter only integers")
OUTPUT
PROGRAM – 5 b
AIM: Python program to define a custom exception class which takes a string message as attribute.
ALGORITHM:
1. Start
2. Create a base class using class Error(Exception): pass
3. Create a subclass using class ValueTooSmallError(Error): pass
4. Create a subclass using class ValueTooLargeError(Error): pass
5. Write the following code to use the user-defined exceptions created above
number = 10
while True:
try:
i_num = int(input("Enter a number: "))
if i_num< number:
raise ValueTooSmallError
elifi_num> number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()
print("Congratulations! You guessed it correctly.")
6. End
SOURCE CODE:
#define a custom exception class which takes a string message as attribute
class Error(Exception): pass
class ValueTooSmallError(Error): pass
class ValueTooLargeError(Error): pass
number = 15
while True:
try:
i_num = int(input("Guess the number:"))
if i_num< number:
raise ValueTooSmallError
elif i_num> number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
except ValueTooLargeError:
print("This value is too large, try again!")
print("Congratulations! You guessed it correctly")
OUTPUT
VIVA – VOCE
Week – 6
PROGRAM - 6: Write a Python program to implement the following sorting techniques:
a) Insertion sort b) merge sort
PROGRAM – 6 a:
ALGORITHM:
1. Start
2. Read the list of numbers to a variable named alist
3. alist = [int(x) for x in alist]
4. insertion_sort(alist)
5. print('Sorted list: ', end='')
6. print(alist)
7. Stop
SOURCE CODE:
a=list(map(int,input("Enter the elements seperated by space:").split()))
def insertionsort(a):
for i in range(1,len(a)):
j=i
while a[j-1]>a[j] and j>0:
a[j-1],a[j]=a[j],a[j-1]
j-=1
insertionsort(a)
print(a)
OUTPUT:
PROGRAM – 6 b:
ALGORITHM:
SOURCE CODE:
OUTPUT
VIVA – VOCE
1. Define sorting
Sorting is the process of ordering or arranging a given collection of elements in some
particular order. We can sort a collection of numbers in ascending (increasing) or descending
(decreasing) order.
Week – 7
PROGRAM - 7: Write a Python program to implement
a) Stack ADT. b) Queue ADT
PROGRAM – 7 a :
ALGORITHM:
create List
Print the stack operations
Check stack empty or not
If stack is empty print “stack empty”
To push an item in the stack, use the list function append list.append()
To pop an item in the stack, use the list function pop list.pop()
To get the top most item in the stack, write list[-1]
Print stack
SOURCE CODE:
#stack ADT
ch='y'
stack=[]
print("MENU\n1.push\n2.pop\n3.display")
while(ch=='y'):
c=int(input("Enter your choice:"))
if(c==1):
n=int(input("Enter the element:"))
stack.append(n)
elif(c==2):
print("Element deleted is",stack.pop())
elif(c==3):
print(stack)
else:
print("Invalid choice")
ch=input("Do you want to continue(y/n):")
OUTPUT
SOURCE CODE 2:
import sys
class Stack:
def __init__(self):
self.elements = []
self.top=-1
def push(self, data):
self.elements.append(data)
self.top=self.top+1
return data
def pop(self):
self.top=self.top-1
return self.elements.pop()
def peek(self):
return self.elements[-1]
def is_empty(self):
return len(self.elements) == 0
def is_full(self):
return self.top == n-1
def top(self):
return self.top
def display(self):
if self.is_empty():
print("\nStack is Empty");
else:
print("Stack contains\n");
for i in range (0,self.top+1):
print("\t",self.elements[i]);
if __name__ == '__main__':
stack = Stack()
print("STACK IMPLEMENTATION")
n=int(input("Enter size"))
print("STACK IMPLEMENTATION")
print("MENU \n1.PUSH\t2.POP\t3. PEEK\t4.DISPLAY\t5.EXIT")
while True:
ch=int(input("ENTER UR CHOICE"))
if (ch==1):
if(stack.is_full()):
print("stack is full")
else:
item=int(input("Enter value"))
stack.push(item)
print("%d added item in the stack"%item)
#print("Enter ur choice")
if(ch==2):
if stack.is_empty():
print("underflow")
else:
item=stack.pop()
print("%d popped item"%item)
#print("Enter ur choice")
if(ch==3):
if stack.is_empty():
print("Underflow")
else:
item=stack.peek()
print("top element",item)
#print("Enter ur choice")
if(ch==4):
stack.display()
if(ch==5):
sys.exit()
OUTPUT:
PROGRAM – 7 b:
ALGORITHM:
create List
Print the queue operations
Check queue empty or not
If queue is empty print “queue empty”
To enqueue an item in the queue, use the list function append list.append()
To dequeue an item in the queue, use the list function pop list.pop(0)
To get the top most item in the queue, write list[-1]
Print queue
SOURCE CODE:
ch='y'
queue=[]
print("MENU\n1.ENQUEUE\n2.DEQUEUE\n3.DISPLAY")
while(ch=='y'):
c=int(input("Enter your choice:"))
if(c==1):
n=int(input("Enter the element:"))
queue.append(n)
elif(c==2):
print("Element deleted is", queue.pop(0))
elif(c==3):
print(queue)
else:
print("Invalid choice")
ch=input("Do you want to continue(y/n):")
OUTPUT:
SOURCE CODE 2:
import sys
class queue:
def __init__(self):
self.q = []
self.rear=0
self.front=0
def Enqueue(self):
if len(self.q)==size: # check wether the Queue is full or not
print("Queue is Full!!!!")
else:
element=int(input("Enter the element:"))
self.q.append(element)
print(element,"is added to the Queue!")
self.rear+=1
def dequeue(self):
if self.front==self.rear:
print("Queue is Empty!!!")
else:
e=self.q[self.front]
print("element removed!!:",e)
self.front+=1
def display(self):
if self.front==self.rear:
print("\nqueue is Empty");
else:
print(" contains\n");
for i in range (self.front,self.rear):
print("\t",self.q[i]);
print("MENU \n1.insert\t2.remove\t3.DISPLAY\t4.EXIT")
size=int(input("Enter the size of Queue:"))
Q=queue()
while True:
ch=int(input("ENTER UR CHOICE"))
if ch==1:
Q.Enqueue()
elif ch==2:
Q.dequeue()
elif ch==3:
Q.display()
elif ch==4:
break
else:
print("Invalid Option!!!")
OUTPUT:
SOURCE CODE 3:
import sys
class queue:
def __init__(self):
self.q = []
def Enqueue(self):
if len(self.q)==size: # check wether the Queue is full or not
print("Queue is Full!!!!")
else:
element=int(input("Enter the element:"))
self.q.append(element)
print(element,"is added to the Queue!")
def dequeue(self):
if len(self.q)==0:
print("Queue is Empty!!!")
else:
e=self.q.pop(0)
print("element removed!!:",e)
def display(self):
if len(self.q)==0:
print("\nqueue is Empty");
else:
print(" contains");
for i in self.q:
print("\t",i);
print("MENU \n1.insert\t2.remove\t3.DISPLAY\t4.EXIT")
size=int(input("Enter the size of Queue:"))
Q=queue()
while True:
ch=int(input("ENTER UR CHOICE"))
if ch==1:
Q.Enqueue()
elif ch==2:
Q.dequeue()
elif ch==3:
Q.display()
elif ch==4:
break
else:
print("Invalid Option!!!")
OUTPUT:
VIVA – VOCE:
1. Define stack.
A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is
named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of
plates, etc. A real-world stack allows operations at one end only.
4. Define Queue.
A Queue is defined as a linear data structure that is open at both ends and the operations
are performed in First In First Out (FIFO) order.
Week – 8
PROGRAM - 8: Write a Python program to implement the following stack applications:
a) Infix to postfix b) postfix expression evaluation
PROGRAM – 8(A):
of the stack.
Pop '(' from the stack and don't add it in postfix expression.
Else if i is in '*/+-‘:
If stack is empty or top of the stack is '(':
Push the operator in the stack.
Else:
Pop the elements from the stack and continue this until the operator on the top of the
stack has same or less residence then the i.
Else:
Push i in stack.
3. Once we scanned inxexp completely, start popping the elements from the stack and appending
them to postfix expression.
And if we encounter '(' discard it.
SOURCE CODE:
Operators = set(['+', '-', '*', '/', '(', ')', '^']) # collection of Operators
Priority = {'+':1, '-':1, '*':2, '/':2, '^':3} # dictionary having priorities
def infixToPostfix(expression): #a+b
stack = [] # initialization of empty stack
output = '' #ab+
for character in expression:
if character not in Operators: # if an operand append in postfix expression
output+= character#a
elif character=='(': # else Operators push onto stack
stack.append('(')
elif character==')':
while stack and stack[-1]!= '(':
output+=stack.pop()
stack.pop()
else:
while stack and stack[-1]!='(' and Priority[character]<=Priority[stack[-1]]:
output+=stack.pop()
stack.append(character)
while stack:
output+=stack.pop()
return output
expression = input('Enter infix expression ')
print('infix notation: ',expression)
print('postfix notation: ',infixToPostfix(expression))
OUTPUT
PROGRAM – 8 b :
ALGORITHM:
SOURCE CODE:
def postfixEvaluation(s):
st = []
for i in range(len(s)):
c = s[i]
if (c >= '0' and c <= '9'):
temp = int(c)
st.append(temp)
else:
op1 = st.pop()
op2 = st.pop()
if (c == '+'):
st.append(op2 + op1)
elif (c == '-'):
st.append(op2 - op1)
elif (c == '*'):
st.append(op2 * op1)
elif (c == '/'):
st.append(op2 / op1)
return st.pop()
s = input("Enter postfix expression:")
print(postfixEvaluation(s))
OUTPUT
VIVA-VOCE:
(2+(3*5)) = 17
Week – 9
PROGRAM - 9:
Write a Python program that uses functions to perform the following operations on single linked list.
a) Creation b) insertion c) deletion d) traversal
AIM: Python program that uses functions to perform the following operations on single linked list.
a) Creation b) insertion c) deletion d) traversal
ALGORITHM:
1. Create a class Node which has two attributes: data and next. Next is a pointer to the next
node.
2. Create another class which has two attributes: head
3. addNode() will add a new node to the list:
a. Define a node current which initially points to the head of the list.
b. Traverse through the list till current points to null.
c. Display each node by making current to point to node next to it in each iteration.
SOURCE CODE:
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 52
CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT
def __init__(self):
self.head=None
def add_begin(self,data):
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
def add_end(self,data):
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
def add_specific(self,data,pos):
if self.head is None:
self.head = new_node
else:
current=self.head
for i in range(1,pos):
p=current
current=current.next
p.next=new_node
new_node.next=current
def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next
def delete_beg(self):
current=self.head
self.head=current.next
del(current)
def delete_end(self):
current=self.head
while current.next is not None:
p=current
current=current.next
p.next=None
del(current)
def del_specific(self,pos):
current=self.head
for i in range(1,pos-1):
B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 53
CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT
current=current.next
p=current.next
current.next=p.next
del(p)
LL1=LinkedList()
print("1.INSERT AT BEGINING")
print("2.INSERT AT ENDING")
print("3.INSERT AT SPECIFIC POSITION")
print("4.DISPLAY")
print("5.DELETE FROM BEGINING")
print("6.DELETE FROM ENDING")
print("7.DELETE FROM SPECIFIC POSITION")
print("8.EXIT")
while True:
op=int(input("enter your choice"))
match(op):
case 1:
data = int(input('Enter the element:'))
new_node = Node(data)
LL1.add_begin(new_node)
case 2:
data = int(input('Enter the element:'))
new_node = Node(data)
LL1.add_end(new_node)
case 3:
pos=int(input('Enter pos:'))
data = int(input('Enter the element:'))
new_node = Node(data)
LL1.add_specific(new_node,pos)
case 4:
print('The list: ', end = '')
LL1.display()
print()
case 5:
LL1.delete_beg()
case 6:
LL1.delete_end()
case 7:
pos=int(input("enter pos"))
LL1.del_specific(pos)
case 8:
exit()
OUTPUT
VIVA - VOCE
a linked list is a linear collection of data elements whose order is not given by their physical
placement in memory.
Dynamic Data Structure: In LinkedList, memory is dynamically allocated to the LinkedList. ...
Implementation: LinkedList is a very useful Data Structure that helps implement other Data
Structures like Stacks and Queues.
The singly-linked list holds data and a link to the next component. While in a doubly-linked
list, every node includes a link to the previous node.
Circular Linked List is a variation of Linked list in which the first element points to the last
element and the last element points to the first element.
Week – 10
PROGRAM - 10:
Write a Python program that uses functions to perform the following operations on doubly linked list.
a) Creation b) insertion c) deletion d) traversal
AIM: Python program that uses functions to perform the following operations on doubly linked list.
a) Creation b) insertion c) deletion d) traversal
ALGORITHM:
a.Insertion at Beginning
1. START
2. Create a new node with three variables: prev, data, next.
3. Store the new data in the data variable
4. If the list is empty, make the new node as head.
5. Otherwise, link the address of the existing first node to the next variable of the new
node, and assign null to the prev variable.
6. Point the head to the new node.
7. END
b.Deletion
1. START
2. Check the status of the doubly linked list
3. If the list is empty, deletion is not possible
4. If the list is not empty, the head pointer is shifted to the next node.
5. END
SOURCE CODE:
class Node:
def __init__(self,data):
self.data=data
self.prev=None
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def add_begin(self,data):
if self.head is None:
self.head = new_node
else:
self.prev=new_node
B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 57
CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT
new_node.next = self.head
self.head = new_node
def add_end(self,data):
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
new_node.prev=current
current.next = new_node
def add_specific(self,data,pos):
if self.head is None:
self.head = new_node
else:
current=self.head
for i in range(1,pos):
p=current
current=current.next
p.next=new_node
new_node.prev=p
new_node.next=current
current.prev=new_node
def display_forward(self):
current = self.head
while current:
print(current.data, end = '->')
current = current.next
def display_backward(self):
current = self.head
while current.next is not None:
current=current.next
while current is not None:
print(current.data,end="<-")
current=current.prev
print(self.head.data)
def delete_beg(self):
if self.head is None:
print("LIST IS EMPTY")
else:
current=self.head
current.next.prev=None
self.head=current.next
del(current)
def delete_end(self):
current=self.head
if current.next is None:
self.head=None
del(current)
else:
current=self.head
while current.next is not None:
p=current
current=current.next
p.next=None
del(current)
def del_specific(self,pos):
current=self.head
for i in range(1,pos):
p=current
current=current.next
p.next=current.next
current.next.prev=p
del(current)
LL1=LinkedList()
print("1.INSERT AT BEGINING")
print("2.INSERT AT ENDING")
print("3.INSERT AT SPECIFIC POSITION")
print("4.DISPLAY FORWARD")
print("5.DISPLAY BACKWARD")
print("6.DELETE FROM BEGINING")
print("7.DELETE FROM ENDING")
print("8.DELETE FROM SPECIFIC POSITION")
print("9.EXIT")
while True:
op=int(input("enter your choice"))
match(op):
case 1:
data = int(input('Enter the element:'))
new_node = Node(data)
LL1.add_begin(new_node)
case 2:
data = int(input('Enter the element:'))
new_node = Node(data)
LL1.add_end(new_node)
case 3:
pos=int(input('Enter pos:'))
data = int(input('Enter the element:'))
new_node = Node(data)
LL1.add_specific(new_node,pos)
case 4:
print('The list: ', end = '')
LL1.display_forward()
print()
case 5:
print('The list: ', end = '')
LL1.display_backward()
print()
case 6:
LL1.delete_beg()
case 7:
LL1.delete_end()
case 8:
pos=int(input("enter pos"))
LL1.del_specific(pos)
case 9:
exit()
OUTPUT
VIVA - VOCE
yes
Basic Operations
Insertion − Adds an element at the beginning of the list.
Deletion − Deletes an element at the beginning of the list.
Insert Last − Adds an element at the end of the list.
Delete Last − Deletes an element from the end of the list.
Insert After − Adds an element after an item of the list.
a doubly linked list is a linked data structure that consists of a set of sequentially linked records
called nodes. Each node contains three fields: two link fields (references to the previous and to the
next node in the sequence of nodes) and one data field.
Week – 11
PROGRAM - 11:
Write a Python program to traverse the given binary search tree in
a) Pre-order b) in-order c) post-order
AIM: Python program to traverse the given binary search tree in a) pre-order b) in-order c) post-order
ALGORITHM:
A)PRE-ORDER
Until all nodes are traversed −
Step 1 − Visit root node.
Step 2 − Recursively traverse left subtree.
Step 3 − Recursively traverse right subtree.
B)IN-ORDER
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.
C)POST-ORDER
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Recursively traverse right subtree.
Step 3 − Visit root node.
SOURCE CODE:
class BST:
def __init__(self, val=None):
self.left = None
self.right = None
self.val = val
else:
self.left.insert(val)
elif val > self.val:
if self.right is None:
self.right = BST(val)
else:
self.right.insert(val)
else:
self.val = val
a = BST()
print('Menu')
print('1.insert')
print('2.preorder')
print('3.inorder')
print('4.postorder')
print('5.break')
while(True):
ch = int(input('Enter your choice:'))
if(ch == 1):
data = int(input('Enter the element:'))
a.insert(data)
elif(ch == 2):
print('PREORDER',a.preorder([]))
elif(ch == 3):
B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 63
CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT
print('INORDER',a.inorder([]))
elif(ch == 4):
print('POSTORDER',a.postorder([]))
elif(ch == 5):
break
else:
print('Invalid choice')
OUTPUT:
VIVA – VOCE
Binary Tree.
Binary Search Tree
AVL Tree.
B-Tree.
A binary tree is a tree-type non-linear data structure with a maximum of two children for
each parent. Every node in a binary tree has a left and right reference along with the data
element.
Tree traversal means visiting each node of the tree: Inorder, Preorder and Postorder
Each node has a maximum of up to two children.For each node, the values of its left descendent
nodes are less than that of the current node, which in turn is less than the right descendent nodes
The AVL tree structuring is implemented with the three basic data structure operations,
namely search, insert and delete. There are four types of Rotations in the AVL tree: Left
rotation, Right rotation, Left-Right rotation, Right-Left rotation.
Week – 12
PROGRAM - 12: Write a Python Program to implement the following Graph Traversals:
a) BFS b) DFS
PROGRAM – 12 a:
ALGORITHM:
BREADTH FIRST SEARCH
1.Create a queue and insert any one vertex of the graph at the back of the queue.
SOURCE CODE:
def bfs(v):
if len(queue)==0:
queue.append(v)
x=queue.pop(0)
visited.append(x)
for i in adj_list[x]:
if unVisited(i):
queue.append(i)
if len(queue)>0:
bfs(queue[0])
def unVisited(v):
for i in queue:
if i==v:
return False
for i in visited:
if i==v:
return False
return True
adj_list=dict()
v=eval(input("Enter vertices"))
for i in v:
print("Enter the neighbors of ",i)
adj_list[i]=eval(input())
for i in v:
print(i,":",adj_list[i])
def display():
for i in visited:
print(i,end=' ')
adjMat=[]
queue=[]
visited=[]
X=input("Enter start vertex")
bfs(X)
display()
OUTPUT:
SOURCE CODE 2:
#breadth first search(BFS)
graph1 = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : [],
'F' : []
}
graph2 = {
0: [1, 2],
1: [2],
2: [3, 4],
3: [1, 2],
4: []
}
visited = []
queue = []
PROGRAM – 12 b :
ALGORITHM:
1. Start by putting any one of the graph's vertices on top of a stack.
2.Take the top item of the stack and add it to the visited list.
3.Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the top
of the stack.
4.Keep repeating steps 2 and 3 until the stack is empty.
SOURCE CODE:
def dfs(v):
if len(stack)==0:
stack.append(v)
x=stack.pop()
visited.append(x)
for i in adj_list[x]:
if unVisited(i):
stack.append(i)
if len(stack)>0:
dfs(stack[0])
def unVisited(v):
for i in stack:
if i==v:
return False
for i in visited:
if i==v:
return False
return True
adj_list=dict()
v=eval(input("Enter vertices"))
for i in v:
print("Enter the neighbors of ",i)
adj_list[i]=eval(input())
for i in v:
print(i,":",adj_list[i])
def display():
for i in visited:
print(i,end=' ')
adjMat=[]
stack=[]
visited=[]
X=input("Enter start vertex")
dfs(X)
display()
OUTPUT:
1: [2],
2: [3, 4],
3: [1, 2],
4: []
}
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print(node,end=' ')
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
OUTPUT:
VIVA - VOCE
1. What is a graph?
A graph is a common data structure that consists of a finite set of nodes (or vertices) and a set of
edges connecting them. A pair (x,y) is referred to as an edge, which communicates that the x
vertex connects to the y vertex.
A directed acyclic graph (DAG) is a conceptual representation of a series of activities. The order
of the activities is depicted by a graph, which is visually presented as a set of circles, each one
representing an activity, some of which are connected by lines, which represent the flow from
one activity to another.
In graph theory, an adjacency matrix is nothing but a square matrix utilised to describe a finite
graph. The components of the matrix express whether the pairs of a finite set of vertices (also
called nodes) are adjacent in the graph or not.
In graph theory, the degree (or valency) of a vertex of a graph is the number of edges that are
incident to the vertex; in a multigraph, a loop contributes 2 to a vertex's degree, for the two ends
of the edge.
a complete graph is a simple undirected graph in which every pair of distinct vertices is
connected by a unique edge. A complete digraph is a directed graph in which every pair of
distinct vertices is connected by a pair of unique edges (one in each direction).