0% found this document useful (0 votes)
2 views

Data Structures Through Python Lab Record 23-24-IISEM

The document outlines a series of Python programming exercises for a Data Structures lab at CMR Institute of Technology, covering topics such as GCD computation, prime numbers, Fibonacci sequences, factorial calculation, palindrome checking, and basic calculator simulation. It also includes algorithms and source code for linear and binary search methods, along with a section for viva-voce questions related to Python programming concepts. Each program is accompanied by its respective output and explanations of algorithms.

Uploaded by

Swapna T
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Data Structures Through Python Lab Record 23-24-IISEM

The document outlines a series of Python programming exercises for a Data Structures lab at CMR Institute of Technology, covering topics such as GCD computation, prime numbers, Fibonacci sequences, factorial calculation, palindrome checking, and basic calculator simulation. It also includes algorithms and source code for linear and binary search methods, along with a section for viva-voce questions related to Python programming concepts. Each program is accompanied by its respective output and explanations of algorithms.

Uploaded by

Swapna T
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 74

CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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:

AIM: Python program to compute the GCD of two numbers

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)}")
'''

B.Tech – II –SEM DATA STRUCTURES THROUGH PYTHON LAB Page 1


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

OUTPUT

B.Tech – II –SEM DATA STRUCTURES THROUGH PYTHON LAB Page 2


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

PROGRAM – 1b:

AIM: Python program display first “N” prime numbers

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

B.Tech – II –SEM DATA STRUCTURES THROUGH PYTHON LAB Page 3


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

PROGRAM – 1c:

AIM: Python program display first “N” Fibonacci sequence

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

B.Tech – II –SEM DATA STRUCTURES THROUGH PYTHON LAB Page 4


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

print(f3)

OUTPUT

B.Tech – II –SEM DATA STRUCTURES THROUGH PYTHON LAB Page 5


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

PROGRAM – 1d:

AIM: Python program to find the factorial value of a given number

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

B.Tech – II –SEM DATA STRUCTURES THROUGH PYTHON LAB Page 6


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

VIVA - VOCE

1. What type of language is python?

Python is an interpreter, interactive, object-oriented programming language .

2. What are the common built in datatypes in python?


Some built-in Python data types are:
Numeric data types: int, float, complex.
String data types: str.
Sequence types: list, tuple, range.
Binary types: bytes, bytearray, memoryview.
Mapping data type: dict.
Boolean type: bool.
Set d ata types: set, frozenset. Python Numeric Data Type.

3. Name the Repetition structures in python?


A condition-controlled loop –WHILE , count-controlled loop-FOR LOOP

4. List different operators in Python language.

 Arithmetic operators.
 Assignment operators.
 Comparison operators.
 Logical operators.
 Identity operators.
 Membership operators.
 Bitwise operators.

5. List the Python functions and the applications of python.


Functions: len(),sorted,ord(0,print(),input(),type(),id(),max()

Applications Python are Web and Internet Development, Scientific and Numeric, Education,
Desktop GUIs, Software Development, Business Applications.

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 7


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 8


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

PROGRAM – 2 b:

AIM: Write a Python program simulate simple Calculator.

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:

#simulate simple calculator


ch=1
while(ch==1):
print("1.Add")
print("2.Sub")
print("3.Mul")
print("4.Div")
print("5.Modulus")
a=int(input("Enter number1:"))
b=int(input("Enter number2:"))
c=int(input("Enter choice:"))
if(c==1):
print(f"sum of {a} and {b} is {a+b}")
elif(c==2):
print(f"sub of {a} and {b} is {a-b}")
elif(c==3):
print(f"mul of {a} and {b} is {a*b}")
elif(c==4):
print(f"div of {a} and {b} is {a/b}")
elif(c==5):
print(f"div of {a} and {b} is {a%b}")
else:
print("Invalid choice")
ch=int(input("Do u want to continue(1/0):"))

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 9


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

OUTPUT

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 10


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 11


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

PROGRAM – 2 d:

AIM: Python program find the most frequent words in a text.

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:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 12


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

print(key)

OUTPUT

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 13


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

VIVA - VOCE

1. What is the difference between list and tuple?


The primary difference between tuples and lists is that tuples are immutable as opposed to lists which
are mutable. Therefore, it is possible to change a list but not a tuple.

2. What is the difference between string comparison and string ‘n’ comparison?

3. Mention methods used in list.


Append(),clear(),copy(),extend(),count(),index(),insert(),pop(),reverse(),sort(),min(),max()

4. Define Set in python.


A set is a collection which is unordered, unchangeable*, and unindexed.

5. Difference between set and dictionary in python.


A set is a built-in data structure in Python that represents a collection of unique elements. A
Dictionary is a collection of key-value pairs, where each key is unique and associated with a
value.

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 14


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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

a=input('Enter list of numbers seperated by space:').split()


a=[int(x) for x in a]
key=int(input('The number to search for:'))
index=linear_search(a,key)
if(index<0):
print(key,"was not found")
else:
print(key,"was found at index:",index)

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 15


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

OUTPUT

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 16


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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

a=input('Enter list of numbers seperated by space:').split()


a=[int(x) for x in a]
key=int(input('The number to search for: '))
b=a.copy()
a.sort()
index=binary_search(a, key)
if(index<0):
print(key,'was not found')
else:
print(key,'{} was found at index',b.index(key))

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 17


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

OUTPUT

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 18


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

VIVA - VOCE

1. Define searching process.

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.

2. What is the drawback of linear search?

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?

only one comparison is made.

4. Why binary search method is more efficient than linear search?


The main advantage of using binary search is that it does not scan each element in the list.
Instead of scanning each element, it performs the searching to the half of the list. So, the
binary search takes less time to search an element as compared to a linear search.

5. Difference between and non linear data structures.


In a non-linear data structure, data elements are attached in hierarchically manner. 2.
In linear data structure, single level is involved.

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 19


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 20


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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]

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 21


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 23


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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

SOURCE CODE: Week4b-using set:

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:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 26


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 27


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 28


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 29


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

VIVA – VOCE

1. What type is a matrix Python?


A matrix in Python is a rectangular Numpy array. This array has to be two-dimensional. It contains
data stored in the array's rows and columns.

2. List the different ways to multiply two matrices in python.


Use Python Nested List Comprehension to Multiply Matrices
Custom Python Function to Multiply Matrices
NumPy matmul() to Multiply Matrices in Python

3. List the different ways to multiply two matrices in python.


Use Python Nested List Comprehension to Multiply Matrices
Custom Python Function to Multiply Matrices
NumPy matmul() to Multiply Matrices in Python

4. What is the difference between insert () and append() functions.

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.

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 30


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 31


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 32


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 33


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

VIVA – VOCE

1. What is an exception in Python?


An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions.

2. What is the use of try statement in Python?


The try block lets you test a block of code for errors. The except block lets you handle the error.
The else block lets you execute code when there is no error. The finally block lets you execute code,
regardless of the result of the try- and except blocks.

3. What is the use of except statement in Python?


except is used to catch and handle the exception(s) that are encountered in the try clause. else lets
you code sections that should run only when no exceptions are encountered in the try clause.

4. How do you catch multiple exceptions at once?


When catching multiple exceptions in a single catch block, the rule is generalized to specialized. This
means that if there is a hierarchy of exceptions in the catch block, we can catch the base exception
only instead of catching multiple specialized exceptions.

5. List some examples of built-in exceptions in Python?


Built-in Exceptions
Exception Description

KeyError Raised when a key does not exist in a dictionary

KeyboardInterrupt Raised when the user presses Ctrl+c, Ctrl+z or Delete

LookupError Raised when errors raised cant be found

MemoryError Raised when a program runs out of memory

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 34


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

Week – 6
PROGRAM - 6: Write a Python program to implement the following sorting techniques:
a) Insertion sort b) merge sort
PROGRAM – 6 a:

AIM: Python program to implement Insertion sort

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:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 35


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

PROGRAM – 6 b:

AIM: Python program to implement merge sort

ALGORITHM:

Algorithm for Merge Sort:


1. Start
2. Read the list of numbers to a variable named alist
3. alist = [int(x) for x in alist]
4. merge_sort(alist, 0, len(alist))
5. print('Sorted list: ', end='')
6. print(alist)
7. End

SOURCE CODE:

a=list(map(int,input("Enter the elements seperated by space:").split()))


def mergesort(a):
if len(a)>1:
left=a[:len(a)//2]
right=a[len(a)//2:]
mergesort(left)
mergesort(right)
i=j=k=0
while i<len(left) and j<len(right):
if left[i]<right[j]:
a[k]=left[i]
i+=1
k+=1
else:
a[k]=right[j]
j+=1
k+=1
while i<len(left):
a[k]=left[i]
i+=1
k+=1
while j<len(right):
a[k]=right[j]
j+=1
k+=1
mergesort(a)
print(a)
B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 36
CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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.

2. Write the Time complexity of insertion sort.


The best-case time complexity of insertion sort algorithm is O(n) time complexity. Meaning that the
time taken to sort a list is proportional to the number of elements in the list; this is the case when the list
is already in the correct order.

3. Write the Time complexity of merge sort.


Time Complexity. Merge Sort is a recursive algorithm and time complexity can be expressed as
following recurrence relation. T(n) = 2T(n/2) + O(n) The solution of the above recurrence is O(nLogn).

4. Which sorting technique is more efficient?


Quick sort
5. Merge sort works on which principle?
Merge sort based on the divide-and-conquer strategy. Merge sort continuously cuts down a
list into multiple sublists until each has only one item, then merges those sublists into a sorted
list.

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 37


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

Week – 7
PROGRAM - 7: Write a Python program to implement
a) Stack ADT. b) Queue ADT
PROGRAM – 7 a :

AIM: Python program to implement stack ADT.

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

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 38


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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()

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 39


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 40


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

PROGRAM – 7 b:

AIM: Python program to implement Queue ADT.

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:"))

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 41


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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!!!")

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 42


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 43


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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");

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 44


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 45


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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.

2. Write the condition for stack overflow and underflow


Overflow condition: When stack is completely full (i.e. TOP= MaxSize -1 ) and we try to insert
more element onto stack then this condition is called overflow condition and no further element
could be inserted now until any element is deleted.

3. List the applications of stack


Application of the Stack
 A Stack can be used for evaluating expressions consisting of operands and operators.
 Stacks can be used for Backtracking, i.e., to check parenthesis matching in an expression.
 It can also be used to convert one form of expression to another form.
 It can be used for systematic Memory Management.

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 46


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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.

5. Write the condition for Queue overflow and Queue underflow


we check for underflow condition. An underflow occurs if REAR = –1 or REAR > FRONT
we check for underflow condition. An underflow occurs if FRONT = –1 or FRONT > REAR

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):

AIM: Python program to implement Infix to postfix.

1. Accept infix expression as a string inxexp.


2. For i in inxexp:
If i is alphabet or digit:
Append it to the postfix expression
Else if i is '(':
Push '(' in the stack
Else if i is ')':
Pop the element from the stack and append it postfix expression until we get ')' on top

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 47


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 48


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

PROGRAM – 8 b :

AIM: Python program to implement postfix expression evaluation

ALGORITHM:

1. Declare stack as empty


2. Read input as postfix expression
3. If reading symbol is operand push to stack
4. If reading symbol is operator perform two pop operations
5. Evaluate the expression with operand1 & operand 2
6. Again push back result to the stack
7. Print result
B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 49
CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 50


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

VIVA-VOCE:

1. The infix form of the postfix expression ABC-/D*E+ is


ABC*EF-/+
2. Explain infix / postfix in Stack ?
Infix notation is the notation in which operators come between the required operands.
A postfix expression is a collection of operators and operands in which the operator is placed
after the operands. That means, in a postfix expression the operator follows the operands.

3. Give postfix form for (A+B)*C/D


AB+C*D/
4. Give postfix form for A+B/C-D
A+B/C-D
5. Evaluate the following Expression 3 2 3 5 * + /

(2+(3*5)) = 17

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 51


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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. Create a new node.


b. It first checks, whether the head is equal to null which means the list is empty.
c. If the list is empty, head will point to the newly added node.
d. If the list is not empty, the new node will be added to end of the list such that tail's
next will point to the newly added node. This new node will become the new tail of
the list.
delNode() will delete a node from the list:
a. It first assumes current=self.head and self.head=current.next and deletes the current
node by using del(current).

display() will display the nodes present in 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()

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 54


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

OUTPUT

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 55


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

VIVA - VOCE

1. Define linked list? How many types of linked list exists?

a linked list is a linear collection of data elements whose order is not given by their physical
placement in memory.

2. Mention few advantages of linked list?

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.

3. Differentiate between single and double linked list?

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.

4. What are operations performed in single linked list?

Traversal - access each element of the linked list.

 Insertion - adds a new element to the linked list.


 Deletion - removes the existing elements.
 Search - find a node in the linked list.
 Sort - sort the nodes of the linked list

5. What is circular linked list?

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.

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 56


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 58


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 59


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 60


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

VIVA - VOCE

1. Is doubly linked list a two way list?

yes

2. What is another name for double linked list?


Two way linked list

3. What are the operations performed in double linked list?

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.

4. How do you add an item to the end of a doubly linked list?


Algorithm
 Step 1: IF PTR = NULL.
 Step 2: SET NEW_NODE = PTR.
 Step 3: SET PTR = PTR -> NEXT.
 Step 4: SET NEW_NODE -> DATA = VAL.
 Step 5: SET NEW_NODE -> NEXT = NULL.
 Step 6: SET TEMP = START.
 Step 7: Repeat
 Step 8 while TEMP -> NEXT != NULL.
 Step 9: SET TEMP = TEMP -> NEXT.

5. A doubly linked list contains how many fields?

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.

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 61


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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

def insert(self, val):


if self.val is not None:
if val < self.val:
if self.left is None:
self.left = BST(val)
B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 62
CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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

def preorder(self, vals):


if self.val is not None:
vals.append(self.val)
if self.left is not None:
self.left.preorder(vals)
if self.right is not None:
self.right.preorder(vals)
return vals

def inorder(self, vals):


if self.left is not None:
self.left.inorder(vals)
if self.val is not None:
vals.append(self.val)
if self.right is not None:
self.right.inorder(vals)
return vals

def postorder(self, vals):


if self.left is not None:
self.left.postorder(vals)
if self.right is not None:
self.right.postorder(vals)
if self.val is not None:
vals.append(self.val)
return vals

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')

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 64


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

OUTPUT:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 65


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

VIVA – VOCE

1. List the types of trees?

 Binary Tree.
 Binary Search Tree
 AVL Tree.
 B-Tree.

2. Define binary 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.

3. What are tree traversals techniques?

Tree traversal means visiting each node of the tree: Inorder, Preorder and Postorder

4. What are the properties of binary search tree?

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

5. List the operations performed on AVL-tree?

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.

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 66


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

Week – 12
PROGRAM - 12: Write a Python Program to implement the following Graph Traversals:

a) BFS b) DFS

PROGRAM – 12 a:

AIM: Python Program to implement BFS

ALGORITHM:
BREADTH FIRST SEARCH

1.Create a queue and insert any one vertex of the graph at the back of the queue.

2.Initialize a visited array and mark that vertex as visited.

3.Follow the below process till the queue becomes empty:

o Remove a front vertex from the queue.


o Get all the adjacent vertices of the removed vertex.
o If the adjacent vertex has not been visited, mark it as visited and insert it 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"))

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 67


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 68


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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 = []

def bfs(visited, graph, node):


visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
bfs(visited, graph1, 'A')
print()
bfs(visited, graph2, 0)

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 69


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 70


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

PROGRAM – 12 b :

AIM: Python Program to implement DFS

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():

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 71


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

for i in visited:
print(i,end=' ')

adjMat=[]
stack=[]
visited=[]
X=input("Enter start vertex")
dfs(X)
display()

OUTPUT:

SOURCE CODE (2)


#depth first search(DFS)
graph1 = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : [],
'F' : []
}
graph2 = {
0: [1, 2],

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 72


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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)

dfs(visited, graph1, 'A')


print()
dfs(visited, graph2, 0)
print()

OUTPUT:

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 73


CMR INSTITUTE OF TECHNOLOGY EXPLORE TO INVENT

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.

2. What do you mean by directed a cyclic graph?

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.

3. What is adjacent matrix?

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.

4. What is a degree of a graph?

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.

5. What do you understand by the term complete graph?

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).

B.Tech – II SEM DATA STRUCTURES THROUGH PYTHON LAB Page 74

You might also like