Data Structures Using Python Lab
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 getName(self):
return [Link] def
getPetals(self):
return [Link] def
getPrice(self):
return [Link]
Program:
@abstractmethod def
perimeter(self):
pass
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]()
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]())
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 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.
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)
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])
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:
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:
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:
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:
Output:
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:
Output:
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:
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:
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:
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:
Output:
Output:
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
t = x[pivot]
x[pivot] = x[up]
x[up] = t
return up
return x
for i in range(num):
[Link](int(input()))
print('Sorted list is ')
res = quicksort(list1, 0, num-1)
for i in range(num):
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]")
Output:
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:
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]")
Output:
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:
Program:
class Node:
def init (self, data=None):
[Link] = data
[Link] = None
class SLinkedList:
def init (self):
[Link] = None
def RemoveNodeAtEnd(self):
temp = [Link]
if temp==None:
print("List Empty")
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
print("While")
prev = cur
cur = [Link]
count = count+1
temp = [Link]
if Loc != -1:
print(key ,"Found at Location ",Loc)
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:
[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:
Program:
class Node:
def init (self, data=None):
[Link] = data
[Link] = None
[Link] = None
class DLinkedList:
def init (self):
[Link] = None
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 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
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:
#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 ")
Program:
class BSTNode:
def init (self, val=None):
[Link] = None
[Link] = None
[Link] = val
if [Link] == 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]
[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
print("postorder:")
print([Link]([]))
print("#")
print("inorder:")
print([Link]([]))
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: