0% found this document useful (0 votes)
20 views27 pages

Advanced Data Structures Lab

Advanced Data Structures Lab Manual

Uploaded by

19wh1a1256
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)
20 views27 pages

Advanced Data Structures Lab

Advanced Data Structures Lab Manual

Uploaded by

19wh1a1256
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
You are on page 1/ 27

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:
def init (self, name, petals, price):
self.name = name
self.petals = petals
self.price = price

def set_name(self, name):


self.name = name

def set_petals(self, petals):


self.petals = petals

def set_price(self, price):


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)

# Displaying initial values


print("Flower Name:", rose.get_name())
print("Number of Petals:", rose.get_petals())
print("Price:", rose.get_price())

# Updating values
rose.set_name("Red Rose")
rose.set_petals(24)
rose.set_price(2.99)

# Displaying updated values


print("\nUpdated Flower Name:", rose.get_name())
print("Updated Number of Petals:", rose.get_petals())
print("Updated Price:", rose.get_price())

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****

from abc import ABC, abstractmethod

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:

# Create a list of squares for numbers from 0 to 9

squares = [x**2 for x in range(10)]


print(squares)

b) Dictionary Comprehensions:

# Create a dictionary of squares for numbers from 0 to 4

squares_dict = {x: x**2 for x in range(5)}


print(squares_dict)

c) Set Comprehensions:

# Create a set of even numbers from 0 to 9

even_set = {x for x in range(10) if x % 2 == 0}


print(even_set)

d) Generator Comprehensions:

# Create a generator for even numbers from 0 to 9

even_gen = (x for x in range(10) if x % 2 == 0)


for num in even_gen:
print(num, end=" ")

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]

# Specify the value of 'n' for combinations


n=2

# Generate combinations of 'n' distinct objects


combinations_list = list(combinations(original_list, n))

# Print the combinations


for combo in combinations_list:
print(combo)

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

# Example usage (assuming the array is sorted):

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


target = 6
result = binary_search(arr,
target) if result != -1:
print(f"Element {target} found at index {result}.")
else:
print(f"Element {target} not found in the list.")

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***

Singly Linked List


class Node:
def init
(self,data):
self.data=data
self.next=None
class SinglyLinkedList:
def init (self):
self.head=None
def
is_empty(self):
return self.head is
None def
append(self,data):
new_node=Node(data
)
if self.head is None:
self.head = new_node
else:
current=self.head
while current.next:
current=current.n
ext
current.next=new_n
ode def
prepend(self,data):
new_node=Node(data)
new_node.next=self.he
ad
self.head=new_node
def delete(self,data):
if self.head and
self.head.data==data:
self.head=self.head.next
return
current=self.he
ad while
current.next:
if current.next.data==data:
current.next=current.next.ne
xt return
current=current.
next def
display(self):
current=self.head
while current:
print(current.data,
end="->")
current=current.next
print("None")
#Example usage:
linked_list=SinglyLinkedL
ist() linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.display()
linked_list.prepend(0)
linked_list.display()
linked_list.delete(2)
linked_list.display()

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 append(self, data):


new_node =
Node(data) if
self.head is None:
self.head =
new_node else:
current =
self.head while
current.next:
current = current.next
current.next = new_node
new_node.prev = current

def prepend(self, data):


new_node =
Node(data)
new_node.next =
self.head self.head.prev
= new_node self.head
= new_node
def delete(self,
data): current =
self.head while
current:
if current.data ==
data: if
current.prev:
current.prev.next =
current.next else:
self.head =
current.next if
current.next:
current.next.prev =
current.prev return
current = current.next

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 insert(self, root,


key): if root is
None:
return
TreeNode(key) else:
if key < root.val:
root.left =
self.insert(root.left, key) else:
root.right =
self.insert(root.right, key) return
root

def inorder_traversal(self,
root): if root:
self.inorder_traversal(root.left)
print(root.val, end=' ')
self.inorder_traversal(root.right)

def search(self, root, key):


if root is None or root.val ==
key: return root
if root.val < key:
return self.search(root.right,
key) return
self.search(root.left, key)

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

# Print inorder traversal of the


BST print("Inorder Traversal:")
bst.inorder_traversal(root)
print()

# Search for a key in the


BST search_key = 7
result = bst.search(root,
search_key) if result:
print(f"{search_key} found in the
BST.") else:
print(f"{search_key} not found in the BST.")

output:
Inorder Traversal:
1 3 4 6 7 8 10 13 14
7 found in the BST.

You might also like