0% found this document useful (0 votes)
4 views49 pages

Data Structures Using Python Lab

The document outlines various Python programming tasks related to data structures, including creating classes with instance variables, implementing inheritance with abstract classes, demonstrating method overloading and overriding, and using comprehensions. It provides code examples for each task, such as a Flower class, Polygon hierarchy, and different types of comprehensions. Additionally, it includes a program for generating combinations of distinct objects from a list.

Uploaded by

researchblend
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views49 pages

Data Structures Using Python Lab

The document outlines various Python programming tasks related to data structures, including creating classes with instance variables, implementing inheritance with abstract classes, demonstrating method overloading and overriding, and using comprehensions. It provides code examples for each task, such as a Flower class, Polygon hierarchy, and different types of comprehensions. Additionally, it includes a program for generating combinations of distinct objects from a list.

Uploaded by

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

DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB

1. Write a Python program for class, Flower, that has three instance variables of type str, int,
and float, that respectively represent the name of the flower, its number of petals, and
its price. Your class must include a constructor method that initializes each variable to an
appropriate value, and your class should include methods for setting the value of each
type, and retrieving the value of each type.

Program:-

class Flower:
#Common base class for all Flowers
def init (self, petalName, petalNumber, petalPrice):
[Link] = petalName
[Link] = petalNumber [Link] = petalPrice

def setName(self, petalName): [Link] =


petalName
def setPetals(self, petalNumber): [Link] =
petalNumber

def setPrice(self, petalPrice): [Link] =


petalPrice

def getName(self):
return [Link] def
getPetals(self):
return [Link] def
getPrice(self):
return [Link]

#This would create first object of Flower


class f1 = Flower("Sunflower", 2, 1000)
print ("Flower Details:")
print ("Name: ", [Link]())
print ("Number of petals:", [Link]()) print ("Price:",[Link]())
print ("\n")

#This would create second object of Flower


class f2 = Flower("Rose", 5, 2000)
[Link](3333)
[Link](6)
print ("Flower Details:")
print ("Name: ", [Link]())
print ("Number of petals:", [Link]())
print ("Price:",[Link]())

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 1


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 2


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
2. Develop an inheritance hierarchy based upon a Polygon class that has abstract methods
area( ) and perimeter( ). Implement classes Triangle, Quadrilateral, Pentagon, that
extend this base class, with the obvious meanings for the area( ) and perimeter( )
methods. Write a simple program that allows users to create polygons of the various
types and input their geometric dimensions, and the program then outputs their area
and perimeter.

Program:

from abc import abstractmethod, ABCMeta import math class


Polygon(metaclass = ABCMeta):
def init (self, side_lengths = [1,1,1], num_sides = 3):
self._side_lengths = side_lengths
self._num_sizes = 3

@abstractmethod def area(self):


pass

@abstractmethod def
perimeter(self):
pass

def repr (self):


return (str(self._side_lengths))

class Triangle(Polygon):
def init (self, side_lengths):
super(). init (side_lengths, 3) self._perimeter
= [Link]()
self._area = [Link]()

def perimeter(self):
return(sum(self._side_lengths)) def
area(self):
#Area of Triangle
s = self._perimeter/2 product = s
for i in self._side_lengths: product*=(s-i)
return product**0.5

class Quadrilateral(Polygon):
def init (self, side_lengths):
super(). init (side_lengths, 4) self._perimeter =
[Link]()
self._area = [Link]()

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 3


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
def perimeter(self):
return(sum(self._side_lengths))

def area(self):
# Area of an irregular Quadrilateral
semiperimeter = sum(self._side_lengths) / 2
return [Link]((semiperimeter - self._side_lengths[0]) * (semiperimeter - self._side_lengths[1])
* (semiperimeter - self._side_lengths[2]) * (semiperimeter -
self._side_lengths[3]))

class Pentagon(Polygon):
def init (self, side_lengths):
super(). init (side_lengths, 5)
self._perimeter = [Link]()
self._area = [Link]()

def perimeter(self):
return((self._side_lengths) * 5)

def area(self):
# Area of a regular Pentagon a =
self._side_lengths
return ([Link](5*(5 + 2 * ([Link](5)))) * a * a) / 4

#object of Triangle t1 =
Triangle([1,2,2])
print([Link](), [Link]())

#object of Quadrilateral
q1 = Quadrilateral([1,1,1,1])
print([Link](), [Link]())

#object of Pentagon p1 = Pentagon(1)


print([Link](), [Link]())

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 4


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 5


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
3. Write a python program to implement method overloading and method
overriding.

Method Overloading
Method overloading is an OOPS concept which provides ability to have several methods having the
same name with in the class where the methods differ in types or number of arguments passed.

Method overloading in Python

Method overloading in its traditional sense (as defined above) as exists in other languages like
method overloading in Java doesn’t exist in Python.

In Python if you try to overload a function by having two or more functions having the same name but
different number of arguments only the last defined function is recognized, calling any other
overloaded function results in an error.

Achieving method overloading

Since using the same method name again to overload the method is not possible in Python, so
achieving method overloading in Python is done by having a single method with several parameters.
Then you need to check the actual number of arguments passed to the method and perform the
operation accordingly.

Program:

class OverloadDemo:
# sum method with default as None for parameters def sum(self,
a=None, b=None, c=None):
# When three params are passed
if a!=None and b!=None and c!=None: s = a + b + c
print('Sum = ', s)
# When two params are passed elif a!=None
and b!=None:
s = a + b print('Sum = ', s)

od = OverloadDemo()
[Link](7, 8)
[Link](7, 8, 9)

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 6


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 7


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Method overriding - Polymorphism through inheritance

Method overriding provides ability to change the implementation of a method in a child class which is
already defined in one of its super class. If there is a method in a super class and method having
the same name and same number of arguments in a child class then the child class method is said to be
overriding the parent class method.

When the method is called with parent class object, method of the parent class is executed. When
method is called with child class object, method of the child class is executed. So the appropriate
overridden method is called based on the object type, which is an example of Polymorphism.

Program:
class Person:
def init (self, name, age): [Link] =
name [Link] = age

def displayData(self):
print('In parent class displayData method') print([Link])
print([Link])

class Employee(Person):
def init (self, name, age, id):
# calling constructor of super class super(). init
(name, age) [Link] = id

def displayData(self):
print('In child class displayData method')
print([Link])
print([Link]) print([Link])

#Person class object


person = Person('Karthik Shaurya', 26) [Link]()
#Employee class object
emp = Employee(''Karthik Shaurya', 26, 'E317')
[Link]()

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 8


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 9


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
4. Write a Python program to illustrate the following comprehensions:
a) List Comprehensions
b) Dictionary Comprehensions
c) Set Comprehensions
d) Generator Comprehensions

Comprehensions in Python
Comprehensions in Python provide us with a short and concise way to construct new sequences (such as
lists, set, dictionary etc.) using sequences which have been already defined. Python supports the
following 4 types of comprehensions:
a) List Comprehensions
b)Dictionary Comprehensions
c)Set Comprehensions
d)Generator Comprehensions

a) List Comprehensions:
List Comprehensions provide an elegant way to create new lists. The following is the basic structure
of a list comprehension:

output_list = [output_exp for var in input_list if (var satisfies this condition)]

Note that list comprehension may or may not contain an if condition. List
comprehensions can contain multiple for (nested list comprehensions).

Example: Suppose we want to create an output list which contains only the even numbers which
are present in the input list. Let’s see how to do this using for loop and list comprehension and
decide which method suits better.

Using Loop:

#Constructing output list WITHOUT using List comprehensions input_list = [1,


2, 3, 4, 4, 5, 6, 7, 7]
output_list = []
#Using loop for constructing output list for var in
input_list:
if var % 2 == 0:
output_list.append(var) print(“Output List
using for loop:”, output_list)
Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 10


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Using List Comprehension:

# Using List comprehensions # for


constructing output list
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
list_using_comp = [var for var in input_list if var % 2 == 0]
print("Output List using list comprehensions:",list_using_comp)

Output:

b) Dictionary Comprehensions
Extending the idea of list comprehensions, we can also create a dictionary using dictionary
comprehensions. The basic structure of a dictionary comprehension looks like below.
output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}

Example 1: Suppose we want to create an output dictionary which contains only the odd
numbers that are present in the input list as keys and their cubes as values. Let’s see how to
do this using for loops and dictionary comprehension.

Using Loop:
input_list = [1, 2, 3, 4, 5, 6, 7] output_dict = {}
# Using loop for constructing output dictionary for var in
input_list:
if var % 2 != 0:
output_dict[var] = var**3
print("Output Dictionary using for loop:",output_dict)

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 11


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Using Dictionary Comprehension:

# Using Dictionary comprehensions


# for constructing output dictionary
input_list = [1,2,3,4,5,6,7]
dict_using_comp = {var:var ** 3 for var in input_list if var % 2 != 0}
print("Output Dictionary using dictionary comprehensions:", dict_using_comp)

Output:

Example 2: Given two lists containing the names of states and their corresponding capitals, construct
a dictionary which maps the states with their respective capitals. Let’s see how to do this using for
loops and dictionary comprehension.
Using Loop:

state = ['Gujarat', 'Maharashtra', 'Rajasthan'] capital = ['Gandhinagar', 'Mumbai', 'Jaipur']


output_dict = {}
# Using loop for constructing output dictionary for (key,
value) in zip(state, capital):
output_dict[key] = value
print("Output Dictionary using for loop:", output_dict)

Output:

Using Dictionary Comprehension


# Using Dictionary comprehensions
# for constructing output dictionary
state = ['Gujarat', 'Maharashtra', 'Rajasthan']
capital = ['Gandhinagar', 'Mumbai', 'Jaipur']
dict_using_comp = {key:value for (key, value) in zip(state, capital)}
print("Output Dictionary using dictionary comprehensions:",dict_using_comp)

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 12


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
c) Set Comprehensions:

Set comprehensions are pretty similar to list comprehensions. The only difference between them is
that set comprehensions use curly brackets { }. Let’s look at the following example to understand set
comprehensions.
Example : Suppose we want to create an output set which contains only the even numbers that
are present in the input list. Note that set will discard all the duplicate values. Let’s see how we can do
this using for loops and set comprehension.
Using Loop:

input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
output_set = set()
# Using loop for constructing output set
for var in input_list:
if var % 2 == 0:
output_set.add(var)
print("Output Set using for loop:", output_set)

Output:

Using Set Comprehension:

# Using Set comprehensions # for


constructing output set
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
set_using_comp = {var for var in input_list if var % 2 == 0} print("Output Set
using set comprehensions:",set_using_comp)

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 13


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
d) Generator Comprehensions:
Generator Comprehensions are very similar to list comprehensions. One difference between them is
that generator comprehensions use circular brackets whereas list comprehensions use square
brackets. The major difference between them is that generators don’t allocate memory for the whole
list. Instead, they generate each value one by one which is why theyare memory efficient. Let’s
look at the following example to understand generator comprehension:

input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
output_gen = (var for var in input_list if var % 2 == 0)
print("Output values using generator comprehensions:", end = ' ')
for var in output_gen:
print(var, end = ' ')

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 14


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
5. Write a Python program to generate the combinations of n distinct objects taken from the
elements of a given list. Example: Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9] Combinations of 2
distinct objects: [1, 2] [1, 3] [1, 4] [1, 5] [7, 8] [7, 9] [8, 9].

Program:
from itertools import combinations
def generate_combinations(original_list, n):
# Generate combinations of n distinct objects from the original_list
comb = combinations(original_list, n)
# Print the combinations
print(f"Combinations of {n} distinct objects:")
for c in comb:
print(list(c))
# Example usage:
original_list = [1, 2, 3, 4, 5, 6, 7]
n=2
generate_combinations(original_list, n)

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 15


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
6. Write a program for Linear Search and Binary search

Linear Search Program:


def linearSearch(target, List):
position = 0
global iterations
iterations = 0
while position < len(List):
iterations += 1 # Indented this line to be inside the while loop
if target == List[position]:
return position
position += 1
return -1

if __name__ == '__main__':
List = [1, 2, 3, 4, 5, 6, 7, 8]
target = 3
answer = linearSearch(target, List)
if answer != -1:
print('Target found at index :', answer, 'in',
iterations,'iterations')
else:
print('Target not found in the list')

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 16


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Binary Search Program

def binarySearch(target, List):

left = 0
right = len(List) - 1
global iterations
iterations = 0
while left <= right:
# The following line was not indented correctly
iterations += 1
mid = (left + right) // 2
if target == List[mid]:
return mid
elif target < List[mid]:
right = mid - 1
else:
left = mid + 1
return -1
if __name__ == '__main__':
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14]
target = 12
answer = binarySearch(target, List)
if(answer != -1):
print('Target',target,'found at position', answer, 'in',
iterations,'iterations')
else:
print('Target not found')

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 17


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
7. Write a program to implement Bubble Sort and Selection Sort

Bubble Sort Program:

from array import *

def bubble_sort(list1, n):


for j in range(len(list1) - 1):
for i in range(len(list1) - 1):
if list1[i] > list1[i + 1]:
t = list1[i]
list1[i] = list1[i+1] list1[i + 1] = t
return list1
ArraySize = int(input('Enter How many Elements to read:'))
list1 = array('i', [])
for i in range(ArraySize):
[Link](int(input()))
print('Sorted list is ')
res=bubble_sort(list1, ArraySize)
for i in range(ArraySize):
print(res[i])

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 18


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Selection Sort Program:
from array import *

def selection_sort(lst1, n):


for i in range(n - 1):
mini = i
for j in range(i+1, n):
if lst1[mini] > lst1[j]:
mini = j
t = lst1[i]
lst1[i] = lst1[mini]
lst1[mini] = t
return lst1
ArraySize = int(input('Enter How many Elements to read:'))
list1 = array('i', [])
for k in range(ArraySize):
[Link](int(input()))
print('Sorted list is ')
res = selection_sort(list1, ArraySize)
for k in range(ArraySize):
print(res[k])

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 19


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
8. Write a program to implement Merge sort and Quick sort.

Merge Sort Program:

from array import *

def mergesort(a, low, high):


temp = array('i', [])
if low < high:
mid = int((low + high) / 2)
mergesort(a, low, mid)
mergesort(a, mid + 1, high)
#CODE FOR MERGING SUB ARRAY'S
i = low
j = mid + 1

while i <= mid and j <= high:


if a[i] <= a[j]:
[Link](a[i]) i = i + 1
else:
[Link](a[j])
j=j+1

if i > mid:
while j <= high:
[Link](a[j])
j=j+1
else:
while i <= mid:
[Link](a[i])
i=i+1
#copying back values from temp array to main array k = low
for z in temp:
a[k] = z
k = k+1

list1 = array('i', [])


num = int(input('Enter How many Elements to read:'))
print("Enter ",num," elements")
for y in range(num):
[Link](int(input()))
print('Sorted list is ') mergesort(list1,
0, num-1)
for y in range(num):
print(list1[y],end=" ")

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 20


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 21


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Quick Sort Program:

from array import *

def partition(x, low, high):


if low < high:
down = low
up = high pivot =
down while down <
up:
while x[down] <= x[pivot] and down < high:
down = down + 1
while x[up] > x[pivot]:
up = up-1
if down < up:
t = x[down]
x[down] = x[up]
x[up] = t

t = x[pivot]
x[pivot] = x[up]
x[up] = t
return up

def quicksort(x, low, high):


if low < high:
p = int(partition(x, low, high))
quicksort(x, low, p - 1)
quicksort(x, p + 1, high)

return x

list1 = array('i', [])


num = int(input('Enter How many Elements to read:'))

for i in range(num):
[Link](int(input()))
print('Sorted list is ')
res = quicksort(list1, 0, num-1)
for i in range(num):

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 22


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
print(res[i], end=" ")

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 23


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 24


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
9. Write a program to implement Stacks and Queues

Stack Program using list:

class Stack:
def init (self):
[Link] = []
[Link] = int(-1)
[Link]=int(3)

def Push(self):
if [Link] == [Link]-1:
print("Stack Full")
else:
val = input("Enter Value to be Pushed")
[Link] = [Link]+1
[Link](val)
print(val,"Pushed on to the stack")
def Pop(self):
if [Link] == -1:
print("Stack is Empty")
else:
val = [Link]([Link])
[Link] = [Link]-1
print(val,"Poped from the stack")
def Peek(self):
if [Link] == -1:
print("Stack is Empty")
else:
print("Topest Element:",[Link][[Link]])
def Display(self):
if [Link] == -1:
print("Stack is Empty")
else:
print("Elements in the Stack are:")
new_lst = [Link][::-1]
for x in new_lst:
print("|", x, "|")
StackObj = Stack() while
True:
print("\n****Operations On Stack ***")
print("[Link]")
print("[Link]")
print("[Link]") print("[Link]")
print("[Link]")

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 25


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
choice = int(input("Enter Your Choice:"))
if choice == 1:
[Link]()
elif choice == 2:
[Link]()
elif choice == 3:
[Link]()
elif choice == 4:
[Link]()
elif choice == 5:
exit(0) else:
print("Invalid Choice! Try Again:")

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 26


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Stack Program using linked list:

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

class Stack:
def init (self):
[Link] = None

def Push(self):
data_in = input("Enter Value to be Pushed")
NewNode = Node(data_in)
[Link] = [Link]
[Link] = NewNode
print(data_in," Pushed on to stack")

def Pop(self):
temp = [Link]
if temp is not None:
[Link] = [Link]
print([Link],"is Deleted from Stack")
emp = None
else:
print("Stack is Empty")

def Peek(self):
temp = [Link]
if temp is None:
print("Stack is Empty")
else:
print("Topest Element:",[Link])

def Display(self):
temp = [Link]
if temp is None:
print("Stack is Empty")
else:
while temp is not None:
print("|", [Link],"|", end="\n")
temp = [Link]

StackObj = Stack()
while True:
ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 27
DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
print("\n****Operations On Stack ***")
print("[Link]")
print("[Link]")
print("[Link]")

print("[Link]")
print("[Link]")
choice = int(input("Enter Your Choice:"))
if choice == 1:
[Link]()
elif choice == 2:
[Link]()
elif choice == 3:
[Link]()
elif choice == 4:
[Link]()
elif choice == 5:
exit(0) else:
print("Invalid Choice! Try Again:")

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 28


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Queue Program using list:

class Queue:
def init (self):
self.Q = []
[Link] = int(-1)
[Link] = int(-1)
[Link] = int(3)

def Enqueue(self):
if [Link]>[Link]:
[Link] = int(-1)
[Link] = int(-1)
self.Q = []
if [Link] == int(([Link]-1)):
print("Queue is Full")
else:
if [Link] == -1:
[Link] = 0
val = input("Enter an Element into Queue")
[Link] = [Link] + 1
[Link](val)
print(val,"Inserted sucessfully into Queue")

def Dequeue(self):
if ([Link]==-1 and [Link]== -1)or([Link]>[Link]):
[Link]=[Link]=-1
self.Q = []
print("Queue is Empty")
else:
val = self.Q[[Link]]
self.Q[[Link]]=""
[Link] = [Link]+1
print(val," is deleted Sucesfully")

def Display(self):
if ([Link]==-1 and [Link]==-1)or([Link]>[Link]):
[Link]=[Link]=-1
print("Queue is Empty")
self.Q = []
else:
for i in range([Link],[Link]+1):
print(self.Q[i],"<--",end="")
Qobj = Queue()

while True:
print("\n****Operations On Stack ***")
print("[Link]")
print("[Link]") print("[Link]")

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 29


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
print("[Link]")
choice = int(input("Enter Your Choice:"))
if choice == 1:
[Link]()
elif choice == 2:
[Link]()
elif choice == 3:
[Link]()
elif choice == 4:
exit(0) else:
print("Invalid Choice! Try Again:")

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 30


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Queue Program using linked list:

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

class Queue:
def init (self):
[Link] = None
[Link] = None
def
Enqueue(self):
temp = [Link]
data_in=input("Enter an Element into Queue")
NewNode = Node(data_in)
if temp is None:
[Link] = NewNode
[Link] = NewNode
else:
while [Link] is not None:
temp = [Link]
[Link] = NewNode
[Link] = NewNode
print(data_in, " Inserted sucessfully into Queue")

def Dequeue(self):
temp = [Link]
if temp is not None: [Link] =
[Link]
print([Link], "is deleted Sucesfully") if [Link]
is [Link]:
[Link]=[Link]=None
temp = None
else:
print("Queue is Empty")

def Display(self):
temp = [Link]
if temp is None:
print("Queue is Empty")
else:
while temp is not None: print([Link],"<--
", end="")
temp = [Link]
Qobj = Queue()
while True:
print("\n****Operations On Stack ***")
print("[Link]")
print("[Link]")
ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 31
DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
print("[Link]")
print("[Link]")
choice = int(input("Enter Your Choice:"))
if choice == 1:
[Link]()
elif choice == 2:
[Link]()
elif choice == 3:
[Link]()
elif choice == 4:
exit(0) else:
print("Invalid Choice! Try Again:")

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 32


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
10. Write a program to implement Singly Linked List

Program:

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

class SLinkedList:
def init (self):
[Link] = None

def InsertAtBeg(self, data_in):


NewNode = Node(data_in) [Link]
= [Link]
[Link] = NewNode
[Link]()

def InsertAtEnd(self, data_in):


temp = [Link]
NewNode = Node(data_in)
if temp is None:
#print("List Empty")
[Link]=NewNode
else:
while [Link] is not None:
temp = [Link]
[Link] = NewNode
[Link]()

# Function to remove node1


def RemoveNodeAtBeg(self):
temp = [Link]
if temp is not None:
[Link] = [Link]
print([Link],"is Deleted from List")
temp = None
else:
print("List is Empty")

def RemoveNodeAtEnd(self):
temp = [Link]
if temp==None:
print("List Empty")

elif [Link] == None:


print([Link], "is Deleted from List")
temp = None

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 33


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
[Link]=None
else:
while [Link] is not None:
prev = temp
temp = [Link]
print([Link],"is Deleted from List")
[Link] = None
temp=None
[Link]()

def TraverseList(self):
temp = [Link]
if temp is None:
print("Linked List is Empty")
else:
while temp is not None:
print("-->", [Link], end="")
temp = [Link]

def NodeCount(self):
count = 0
temp = [Link]
if temp is None:
return count
else:
while temp is not None:
count = count+1
temp = [Link]
return count

def InsertAtPos(self, data_in,pos):


NewNode = Node(data_in)
Nc = int([Link]())
if(pos > Nc and Nc == 0)or(pos > Nc and Nc != 0):
if pos == 1:
[Link] = [Link]
[Link] = NewNode
else:
print("Invalid Position\nTry Again")
else:
cur = [Link]
prev = cur
count = int(1)

while count < pos:

print("While")
prev = cur
cur = [Link]

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 34


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
count = count+1
if pos==1:
[Link] = [Link]
[Link] = NewNode
else:
[Link] = cur
[Link] = NewNode
[Link]()

#Delete a node at a position


def DelAtPos(self, pos):
Nc = int([Link]())
if pos > Nc:
print("Invalid Position\nTry Again")
elif Nc == 0:
print("List is empty")
print("Deletion Not Possible")
elif pos == 1:
temp = [Link]
print([Link], " is Deleted from List")
temp = [Link]
[Link] = temp
else:
cur = [Link]
count = int(1)
while count < pos:
prev = cur
cur = [Link]
count = count+1
temp = cur
[Link]=[Link]
print([Link], " is Deleted from List")
temp = None
#Search
def search(self, key):
count = 1
Loc = int(-1)
temp = [Link]
if temp is None:
print("List is Empty")
else:
while temp is not None:
if key == int([Link]):
Loc = count
break

count = count+1
temp = [Link]
if Loc != -1:
print(key ,"Found at Location ",Loc)

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 35


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
else:
print(key, "NOt Found in the List ")

#Creating Object to List ADT


llist = SLinkedList()

while True:
print("\n****Operations On Single Linked List***")
print("[Link] at Begining")
print("[Link] at End")
print("[Link] at Begining") print("[Link]
at End") print("[Link] the List")
print("[Link] Count")
print("[Link] at a Position")
print("[Link] at a Position")
print("[Link] for a Node")
print("[Link]") choice = int(input("Enter
Your Choice:"))
if choice == 1:
data = input("Enter a Value:")
[Link](data)
elif choice == 2:
data = input("Enter a Value:")
[Link](data)
elif choice == 3:
[Link]()
elif choice == 4:
[Link]()
elif choice == 5:
[Link]()
elif choice == 6:
print("Total nodes in the List:",[Link]())
elif choice == 7:
data = input("Enter a Value:")
nCount=int([Link]())
if nCount==0:
print("Empty List:")
else:
print("Available max position is ",nCount )
pos = int(input("Enter position of insertion:"))
[Link](data, pos)
elif choice == 8:

pos = int(input("Enter position for Deletion:"))

[Link](pos)
elif choice == 9:
keyVal = int(input("Enter key for searching:"))
[Link](keyVal)
elif choice == 10:
exit(0)
ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 36
DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
else:
print("Invalid Choice! Try Again:")

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 37


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 38


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
11. Write a program to implement Doubly Linked list

Program:

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

class DLinkedList:
def init (self):
[Link] = None

def InsertAtBeg(self, data_in):


NewNode = Node(data_in) [Link] =
[Link]
[Link] = NewNode
[Link]()

def InsertAtEnd(self, data_in):


temp = [Link]
NewNode = Node(data_in)
if temp is None:
[Link]=NewNode
else:
while [Link] is not None:
temp = [Link]
[Link] = NewNode
[Link] = temp
[Link]()

# Function to remove node


def RemoveNodeAtBeg(self):
temp = [Link]
if [Link] is None:
print([Link], "is Deleted from List")
temp = None
[Link]=temp
elif temp is not None:
print([Link], "is Deleted from List")
temp = [Link]
[Link]=None
[Link]=temp
temp = None
ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 39
DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
else:
print("List is Empty")
[Link]()

def RemoveNodeAtEnd(self):
temp = [Link]
if temp==None:
print("List is Empty")
elif [Link] == None:
print([Link], "is Deleted from List")
temp = None
[Link]=None
else:
while [Link] is not None:
pr = temp
temp = [Link]
print([Link],"is Deleted from List")
temp = None
[Link] = None
[Link]()

def DisplayList(self):
temp = [Link]
if temp is None:
print("Doubly Linked List is Empty")
else:
while temp is not None:
print("<==>", [Link], end="")
temp = [Link]
print()

def NodeCount(self):
count = 0
temp = [Link]
if temp is None:
return count
else:
while temp is not None:
count = count+1
temp = [Link]
return count

def InsertAtPos(self, data_in,pos):


NewNode = Node(data_in)

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 40


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Nc = int([Link]())
if(pos > Nc and Nc == 0)or(pos > Nc and Nc != 0):
if pos == 1:
[Link] = [Link]
[Link] = NewNode
temp = [Link] if
temp==None:
print("List is Empty") elif
[Link] == None:
print([Link], "is Deleted from List") temp = None
[Link]=None else:
while [Link] is not None:
pr = temp
temp = [Link] print([Link],"is Deleted
from List") temp = None
[Link] = None [Link]()

def DisplayList(self):
temp = [Link] if temp is
None:
print("Doubly Linked List is Empty") else:
while temp is not None: print("<==>",
[Link], end="") temp = [Link]
print()

def NodeCount(self):
count = 0
temp = [Link] if temp is
None: return count
else:
while temp is not None:
count = count+1 temp =
[Link]
return count

def InsertAtPos(self, data_in,pos): NewNode =


Node(data_in)
Nc = int([Link]())
if(pos > Nc and Nc == 0)or(pos > Nc and Nc != 0): if pos == 1:
[Link] = [Link]
[Link] = NewNode
else:
print("Invalid Position\nTry Again")
else:
cr = [Link]
ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 41
DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
pr = cr
count = int(1)
while count < pos:
print("While")
pr = cr
cr = [Link]
count = count+1
if pos==1:
[Link] = [Link]
[Link] = NewNode
else:
[Link] = cr
[Link] = NewNode
[Link]=NewNode
[Link] = pr
[Link]()

#Delete a node at a position


def DelAtPos(self, pos):

Nc = int([Link]())
if pos > Nc:
print("Invalid Position\nTry Again")
elif Nc == 0 :
print("List is empty")
elif pos == 1:
temp = [Link]
print([Link], "is Deleted from List")
temp = [Link]
[Link] = temp
if temp is None:
pass
else:
[Link] = None
temp = None
elif Nc==pos:
temp = [Link]
while [Link] is not None:
pr = temp
temp = [Link]
print([Link], "is Deleted from List")
temp = None
[Link] = None
else:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 42


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
cr = [Link]
pr = cr
count = int(1)
while count < pos:
pr = cr
cr = [Link]
count = count+1
Dnode=cr
print([Link], " is Deleted from List")
Dnode = None
[Link] = [Link]
temp = [Link]
[Link] = pr
[Link]()

#Search
def search(self, key):
count = 1
Loc = int(-
1)
temp = [Link]
if temp is None:
print("List is Empty")
else:
while temp is not None:
if key == int([Link]):
Loc = count
count = count+1
temp = [Link]

if Loc != -1:
print(key ,"Found at Location ",Loc)
else:
print(key, "NOt Found in the List ")

#Creating Object to List ADT


dll = DLinkedList()
while True:
print("****Operations On Doubly Linked List***")
print("[Link] at Begining")
print("[Link] at End")
print("[Link] at Begining")
print("[Link] at End")
print("[Link]")
print("[Link] Count")
ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 43
DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
print("[Link] at a Position")
print("[Link] at a Position")
print("[Link] for a Node")
print("[Link]")
choice = int(input("Enter Your Choice:"))
if choice == 1:
data = input("Enter a Value:")
[Link](data)
elif choice == 2:
data = input("Enter a Value:")
[Link](data)
elif choice == 3:
[Link]()
elif choice == 4:
[Link]()
elif choice == 5:
[Link]()
elif choice == 6:
print("Total nodes in the List:",[Link]())
elif choice == 7:
data=input("Enter a Value:")
nCount=int([Link]()) if
nCount==0:
print("Empty List:")
else:
print("Available max position is ",nCount )
pos = int(input("Enter position of insertion:"))
[Link](data, pos)
elif choice == 8:
pos = int(input("Enter position for Deletion:"))
[Link](pos)
elif choice == 9:
keyVal = int(input("Enter key for searching:"))
[Link](keyVal)
elif choice == 10:
exit(0)
else:
print("Invalid Choice! Try Again:")

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 44


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 45


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
12. Write a program to implement Binary Search Tree

Program:

class BSTNode:
def init (self, val=None):
[Link] = None
[Link] = None
[Link] = val

def insert(self, val):


if not [Link]:
[Link] = val
return

if [Link] == val:
return

if val < [Link]:


if [Link]:
[Link](val)
return
[Link] = BSTNode(val)
return

if [Link]:
[Link](val)
return
[Link] = BSTNode(val)

def get_min(self):
current = self
while [Link] is not None:
current = [Link]
return [Link]

def get_max(self):
current = self
while [Link] is not None:
current = [Link]
return [Link]

def delete(self, val):


if self == None:
return self
if val < [Link]:
if [Link]:
[Link] = [Link](val)
return self

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 46


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
if val > [Link]:
if [Link]:

[Link] = [Link](val)
return self
if [Link] == None:
return [Link]
if [Link] == None:
return [Link]
min_larger_node = [Link]
while min_larger_node.left:
min_larger_node = min_larger_node.left
[Link] = min_larger_node.val
[Link] = [Link](min_larger_node.val)
return self

def exists(self, val):


if val == [Link]:
return True

if val < [Link]:


if [Link] == None:
return False
return [Link](val)

if [Link] == None: return False


return [Link](val)

def preorder(self, vals):


if [Link] is not None:
[Link]([Link])
if [Link] is not None:
[Link](vals)
if [Link] is not None:
[Link](vals)
return vals

def inorder(self, vals):


if [Link] is not None:
[Link](vals)
if [Link] is not None:
[Link]([Link])
if [Link] is not None:
[Link](vals)
return vals

def postorder(self, vals):


if [Link] is not None:
[Link](vals)

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 47


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB
if [Link] is not None:
[Link](vals)
if [Link] is not None:
[Link]([Link])
return vals

nums = [12, 6, 18, 19, 21, 11, 3, 5, 4, 24, 17]


bst = BSTNode()
for num in nums:
[Link](num)
print("preorder:")
print([Link]([]))
print("#")

print("postorder:")
print([Link]([]))
print("#")

print("inorder:")
print([Link]([]))
print("#")

nums = [2, 6, 20]


print("deleting " + str(nums))
for num in nums:
[Link](num)
print("#")

print("4 exists:")
print([Link](4))
print("2 exists:")
print([Link](2))
print("12 exists:")
print([Link](12))
print("18 exists:")
print([Link](18))

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 48


DEPARTMENT OF ECE DATA STRUCTURES USING PYTHON LAB

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A) PAGE | 49

You might also like