DSA Lab
DSA Lab
PROGRAM:
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
curr_dist, node = heapq.heappop(pq)
if curr_dist > distances[node]:
continue
for neighbor, weight in graph[node]:
dist = curr_dist + weight
if dist < distances[neighbor]:
distances[neighbor] = dist
heapq.heappush(pq, (dist, neighbor))
return distances
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('A', 1), ('C', 2), ('D', 5)],
'C': [('A', 4), ('B', 2), ('D', 1)],
'D': [('B', 5), ('C', 1)],
}
result = dijkstra(graph, 'A')
print(result)
OUTPUT:
{'A': 0, 'B': 1, 'C': 3, 'D': 4}
PROGRAM:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
N = int(input("Enter a number: "))
result = factorial(N)
print(f"The factorial of {N} is {result}")
OUTPUT:
Enter a number: 5
The factorial of 5 is 120
PROGRAM:
def prim(graph, start=0):
n = len(graph)
in_mst = [False] * n
key = [float('inf')] * n
key[start] = 0
mst_weight = 0
for _ in range(n):
u = min((key[v], v) for v in range(n) if not in_mst[v])[1]
in_mst[u] = True
mst_weight += key[u]
for v in range(n):
if graph[u][v] and not in_mst[v] and graph[u][v] < key[v]:
key[v] = graph[u][v]
return mst_weight
graph = [
[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]
]
print("Total weight of MST:", prim(graph))
OUTPUT:
Total weight of MST: 16
PROGRAM:
def bubble_sort(arr):
for i in range(len(arr)):
for j in range(0, len(arr) - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
arr = [int(x) for x in input("Enter numbers separated by spaces: ").split()]
bubble_sort(arr)
print("Sorted array:", arr)
OUTPUT:
Enter numbers separated by spaces: 64 34 25 12 22 11 90
Sorted array: [11, 12, 22, 25, 34, 64, 90]
OUTPUT:
DFS Traversal starting from node 1:
124635
BFS Traversal starting from node 1:
123456
B.Write a Python code to sort the N elements using selection sort.
PROGRAM:
def selection_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
if __name__ == "__main__":
# Sample array to sort
arr = [64, 25, 12, 22, 11]
print("Original array:", arr)
selection_sort(arr)
print("Sorted array:", arr)
OUTPUT:
Original array: [64, 25, 12, 22, 11]
Sorted array: [11, 12, 22, 25, 64]
OUTPUT:
Extracted min: 3
OUTPUT:
Found
OUTPUT:
Inorder Traversal:
4251637
B. Write a Python code to find the Fibonacci value of N using
recursive function.
PROGRAM:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
if __name__ == "__main__":
N = int(input("Enter a number N to find the Fibonacci value: "))
result = fibonacci(N)
print(f"Fibonacci value of {N} is: {result}")
OUTPUT:
Enter a number N to find the Fibonacci value: 9
Fibonacci value of 9 is: 34
OUTPUT:
Hash Table:
Index 0: []
Index 1: [['city', 'New York']]
Index 2: []
Index 3: [['name', 'Alice']]
Index 4: [['age', 30]]
Search for 'age': 30
Search for 'country': None
OUTPUT:
List after creation:
11 -> 22 -> 44 -> 55 -> None
List after inserting 33 after 22:
11 -> 22 -> 33 -> 44 -> 55 -> NonE
List after deleting 22:
11 -> 33 -> 44 -> 55 -> None
OUTPUT:
Queue: [10, 20, 30, 40]
Dequeued element: 10
Front element: 20
Queue: [20, 30, 40]
Size of the queue: 3
Is the queue empty? False
Is the queue empty after clearing? True
OUTPUT:
Stack: [10, 20, 30, 40]
Popped element: 40
Top element: 30
Stack: [10, 20, 30]
Size of the stack: 3
Is the stack empty? False
Is the stack empty after clearing? True
OUTPUT:
Element 20 found at index 3.
OUTPUT:
Queue after enqueuing 10, 20, 30: [10, 20, 30]
Front item: 10
Queue size: 3
Dequeue: 10
Queue after dequeuing: [20, 30]
Is the queue empty? False
Dequeue: 20
Dequeue: 30
Is the queue empty? True
OUTPUT:
Original array: [38, 27, 43, 3, 9, 82, 10]
Sorted array: [3, 9, 10, 27, 38, 43, 82]
OUTPUT:
Stack after pushing 10, 20, 30: [10, 20, 30]
Top item (peek): 30
Stack size: 3
Pop: 30
Stack after popping: [10, 20]
Is the stack empty? False
Pop: 20
Pop: 10
Is the stack empty? True
OUTPUT:
Element 13 found at index 6.
OUTPUT:
Element 30 found at index 2.
OUTPUT:
Front element (peek): 10
Dequeued element: 10
Front element after dequeue (peek): 20
4.B. Write a Python code to sort the N elements using quick sort.
PROGRAM:
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quick_sort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
quick_sort(arr, low, pi - 1)
quick_sort(arr, pi + 1, high)
def sort_array(arr):
quick_sort(arr, 0, len(arr) - 1)
return arr
arr = [10, 7, 8, 9, 1, 5]
sorted_arr = sort_array(arr)
print("Sorted array:", sorted_arr)
OUTPUT:
Sorted array: [1, 5, 7, 8, 9, 10]
OUTPUT:
Sorted array: [5, 6, 11, 12, 13]
1. Write a Python code 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 using ADTs.
PROGRAM:
class Flower:
def __init__(self, name: str, petals: int, price: float):
self.name = name
self.petals = petals
self.price = price
def set_name(self, name: str):
self.name = name
def set_petals(self, petals: int):
self.petals = petals
def set_price(self, price: float):
self.price = price
def get_name(self) -> str:
return self.name
def get_petals(self) -> int:
return self.petals
def get_price(self) -> float:
return self.price
flower1 = Flower("Rose", 15, 5.99)
print(f"Flower Name: {flower1.get_name()}")
print(f"Number of Petals: {flower1.get_petals()}")
print(f"Price: ${flower1.get_price()}")
flower1.set_name("Tulip")
flower1.set_petals(10)
flower1.set_price(3.49)
print("\nUpdated Flower Details:")
print(f"Flower Name: {flower1.get_name()}")
print(f"Number of Petals: {flower1.get_petals()}")
print(f"Price: ${flower1.get_price()}")
OUTPUT:
Flower Name: Rose
Number of Petals: 15
Price: $5.99