Advanced Data Structures Lab
Advanced Data Structures Lab
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:
def init (self, name, petals, price):
self.name = name
self.petals = petals
self.price = price
def get_name(self):
return self.name
def get_petals(self):
return self.petals
def get_price(self):
return self.price
# Example usage:
rose = Flower("Rose", 12, 1.99)
# Updating values
rose.set_name("Red Rose")
rose.set_petals(24)
rose.set_price(2.99)
Output:
Hybiscus
5
20.5
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****
class Polygon(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Triangle(Polygon):
def init (self, a, b, c):
self.a = a
self.b = b
self.c = c
def perimeter(self):
return self.a + self.b + self.c
def area(self):
s = self.perimeter() / 2
return (s * (s - self.a) * (s - self.b) * (s - self.c)) ** 0.5
class Quadrilateral(Polygon):
def init (self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
def perimeter(self):
return self.a + self.b + self.c + self.d
def area(self):
# You can implement area calculation based on the specific type of
quadrilateral pass
class Pentagon(Polygon):
def init (self, a, b, c, d, e):
self.a = a
self.b = b
self.c = c
self.d = d
self.e = e
def perimeter(self):
return self.a + self.b + self.c + self.d + self.e
def area(self):
# You can implement area calculation based on the specific type of
pentagon pass
# Main program
if name == " main ":
print("Polygon Area and Perimeter Calculator")
choice = int(input("Enter the number of sides (3 for Triangle, 4 for Quadrilateral, 5 for
Pentagon): "))
if choice == 3:
a, b, c = map(float, input("Enter the sides (comma-separated): ").split(","))
polygon = Triangle(a, b, c)
elif choice == 4:
a, b, c, d = map(float, input("Enter the sides (comma-separated): ").split(","))
polygon = Quadrilateral(a, b, c, d)
elif choice == 5:
a, b, c, d, e = map(float, input("Enter the sides (comma-separated): ").split(","))
polygon = Pentagon(a, b, c, d, e)
else:
print("Unsupported number of sides.")
exit()
print(f"Perimeter: {polygon.perimeter()}")
print(f"Area: {polygon.area()}")
Output:
Polygon area and perimeter calculator
Enter the number of sides (3 for triangle,4 for quadrilateral,5 for pentagon):3
Enter the sides(comma-separated):12,15,20
Perimeter:47.0
Area:89.6656985697
3. Write a python program to implement Method Overloading and Method Overriding.
*** program***
Method Overloading
class Calculator:
def add(self, *args):
return sum(args)
calc = Calculator()
print(calc.add(2, 3))
print(calc.add(2, 3, 4))
Method Overriding
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
animal = Animal()
dog = Dog()
animal.speak()
dog.speak()
output:
method overloding
5
6
method overriding
Animal speaks
Dog barks
4. Write a Python program to illustrate the following comprehensions:
a) List Comprehensions. b) Dictionary Comprehensions.
c) Set Comprehensions. d) Generator Comprehensions.
*** program***
a) List Comprehensions:
b) Dictionary Comprehensions:
c) Set Comprehensions:
d) Generator Comprehensions:
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{0, 2, 4, 6, 8}
02468
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 # Original list
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output:
[1, 2]
[1, 3] [4,5]
[1, 4] [4, 6]
[1, 5] [4, 7]
[1, 6] [4, 8]
[1, 7] [4, 9]
[1, 8] [5, 6]
[1, 9] [5, 7]
[2, 3] [5, 8] [5, 9] [6, 7] [6, 8] [6, 9] [7, 8] [7, 9] [8,9]
[2, 4]
[2, 5]
[2, 6]
[2, 7]
[2, 8]
[2, 9]
[3, 4]
[3, 5]
[3, 6]
[3, 7]
[3, 8]
[3, 9]
6. Write a python program for Linear Search and Binary search.
***program***
Linear Search
def linear_search(arr,
target): for i in
range(len(arr)):
if arr[i] == target:
return i
return -1
# Example usage:
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
target = 6
result = linear_search(arr,
target) if result != -1:
print(f"Element {target} found at index {result}.")
else:
print(f"Element {target} not found in the list.")
Binary Search
def binary_search(arr,
target): low, high = 0,
len(arr) - 1 while low <=
high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Output:
Linear search
Element 6 found at index 7.
Binary search
Element 6 found at index 5.
7. Write a python program to implement Bubble Sort and Selection Sort.
Bubble sort
def
bubble_sort(arr):
n=len(arr)
for i in range(n):
swapped=False
for j in range(0,n-i-1):
if arr[j]>arr[j+1]:
arr[j], arr[j+1]=arr[j+1],arr[j] #swap
elements swapped=True
if not swapped:
break
#Example
usage
arr=[64,34,25,12,22,11,90]
bubble_sort(arr)
print("Sorted array using Bubble sort:",arr)
Selection sort
def selection_sort(arr):
n=len(arr)
for i in range(n):
min_index=i
for j in range(i+1,n):
if arr[j]<arr[min_index]:
min_index=j
arr[i],arr[min_index]=arr[min_index],arr[i] #Swap
elements #Example usage
arr=[64,25,12,22,11]
selection_sort(arr)
print("Sorted arry using Selection sort:",arr)
Output:
Bubble sort
Sorted array using Bubble sort: [12, 22, 11, 25, 34, 64, 90]
Selection sort
Sorted array using Selection sort: [11, 12, 22, 25, 64]
8. Write a python program to implement Merge sort and Quicksort.
***program***
Merge sort
def merge_sort(arr):
if len(arr)>1:
mid=len(arr)//2
left_half=arr[:mid]
right_half=arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i<len(left_half) and
j<len(right_half): if
left_half[i]<right_half[j]:
arr[k]=left_half[i]
i+=1
else:
arr[k]=right_hal
f[j] j+=1
k+=1
while
i<len(left_half):
arr[k]=left_half[i
] i+=1
k+=1
while j<len(right_half):
arr[k]-
right_half[j] j+=1
k+=1
#Example usage
arr=[38,27,43,3,9,82,10
]
merge_sort(arr)
print("Sorted array using Merge Sort:",arr)
Quick Sort
def quick_sort(arr):
if len(arr)<=1:
return arr
pivot=arr[len(arr)//
2]
left=[x for x in arr if
x<pivot] middle=[x for x in
arr if x==pivot] right=[x for
x in arr if x>pivot]
return quick_sort(left)
+middle+quick_sort(right) #Example
usage
arr=[38,27,43,3,9,82,10]
arr=quick_sort(arr)
print("Sorted array using Quick
Sort:",arr) r) print("Sorted array using
Merge Sort:",arr)
Output:
Merge Sort
Sorted array using Merge Sort: [3, 9, 27, 38, 43,
82, 10] Quick Sort
Sorted array using Quick Sort: [3, 9, 10, 27, 38, 43, 82]
9. Write a python program to implement Stacks and Queues.
***program***
Stacks
class Stack:
def init (self):
self.items=[]
def is_empty(self):
return
len(self.items)==0 def
push(self,item):
self.items.append(ite
m) def pop(self):
if not
self.is_empty():
return
self.items.pop()
def peek(self):
if not
self.is_empty():
return
self.items[-1]
def size(self):
return
len(self.items)
#Example usage:
stack=Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print("Stack:",stack.ite
ms)
print("Pop:",stack.pop(
))
print("Peek:",stack.peek())
print("Size:",stack.size())
Queue
from queue import
Queue def
queue_operations():
my_queue=Queue()
my_queue.put(1)
my_queue.put(2)
my_queue.put(3)
print("Queue:",my_queue.queue)
dequeued_element=my_queue.get()
print("Dequeued
element:",dequeued_element)
print("Updated Queue:",my_queue.queue)
if name ==" main
":
queue_operations()
Output:
Stack
Stack: [1, 2, 3]
Pop: 3
Peek: 2
Size: 2
Queu
e
Queue: deque([1, 2, 3])
Dequeued element: 1
Updated Queue:
deque([2, 3])
10. Write a python program to implement a Singly Linked List.
***program***
Output:
Single linked
list 1->None
2-
>None
3-
>None
0-
>None
1-
>None
2-
>None
3-
>None
0-
>None
1-
>None
3-
>None
11. Write a python program to implement a Doubly Linked list.
***program***
class Node:
def init (self, data):
self.data = data
self.next = None
self.prev = None
class
DoublyLinkedList:
def init (self):
self.head = None
def is_empty(self):
return self.head is None
def display(self):
current =
self.head while
current:
print(current.data, end="
<-> ") current =
current.next
print("None")
# Example usage:
doubly_linked_list =
DoublyLinkedList()
doubly_linked_list.append(1)
doubly_linked_list.append(2)
doubly_linked_list.append(3)
doubly_linked_list.display() # Output: 1 <-> 2 <-> 3 <-> None
doubly_linked_list.prepend(0)
doubly_linked_list.display() # Output: 0 <-> 1 <-> 2 <-> 3 <-> None
doubly_linked_list.delete(2)
doubly_linked_list.display() # Output: 0 <-> 1 <-> 3 <-> None
Output:
1 <-> 2 <-> 3 <-> None
0 <-> 1 <-> 2 <-> 3 <-> None
0 <-> 1 <-> 3 <-> None
12. Write a python program to implement Binary Search Tree.
***program***
class TreeNode:
def init (self,
key): self.val =
key self.left =
None self.right
= None
class BST:
def init (self):
self.root =
None
def inorder_traversal(self,
root): if root:
self.inorder_traversal(root.left)
print(root.val, end=' ')
self.inorder_traversal(root.right)
# Example usage:
bst =
BST() root
= None
keys = [8, 3, 10, 1, 6, 14, 4, 7, 13]
for key in keys:
root = bst.insert(root, key)
output:
Inorder Traversal:
1 3 4 6 7 8 10 13 14
7 found in the BST.