0% found this document useful (0 votes)
5 views

AD3271_lab.Answer

The document contains Python code solutions for various data structures and algorithms, including classes for flowers, linked lists, stacks, queues, and trees. It also includes sorting algorithms like insertion sort, selection sort, and quick sort, as well as search algorithms like linear and binary search. Additionally, it covers advanced topics such as hash tables, heaps, graphs, and algorithms like Dijkstra's and Prim's.

Uploaded by

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

AD3271_lab.Answer

The document contains Python code solutions for various data structures and algorithms, including classes for flowers, linked lists, stacks, queues, and trees. It also includes sorting algorithms like insertion sort, selection sort, and quick sort, as well as search algorithms like linear and binary search. Additionally, it covers advanced topics such as hash tables, heaps, graphs, and algorithms like Dijkstra's and Prim's.

Uploaded by

praveen45742006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

AD3271 SET1 - Python Answers (Q1-Q20)

1. Flower Class
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): 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

2a. List ADT & Delete 30


arr = [10, 20, 30, 40, 50]
arr.remove(30)
print(arr)

2b. Insertion Sort


def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr

3a. Linked List using class


class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self): self.head = None

def append(self, data):


if not self.head:
self.head = Node(data)
else:
temp = self.head
while temp.next: temp = temp.next
temp.next = Node(data)

def display(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
3b. Selection Sort
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]: min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr

4a. Stack using ADT


class Stack:
def __init__(self): self.stack = []
def push(self, item): self.stack.append(item)
def pop(self): return self.stack.pop() if self.stack else None
def display(self): print(self.stack)

4b. Quick Sort


def quick_sort(arr):
if len(arr) <= 1: return arr
pivot = arr[0]
less = [x for x in arr[1:] if x <= pivot]
more = [x for x in arr[1:] if x > pivot]
return quick_sort(less) + [pivot] + quick_sort(more)

5a. Queue using ADT


class Queue:
def __init__(self): self.queue = []
def enqueue(self, item): self.queue.append(item)
def dequeue(self): return self.queue.pop(0) if self.queue else None
def display(self): print(self.queue)

5b. Bubble Sort


def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j]
return arr

6a. Linked List (same as 3a)


6b. Linear Search
def linear_search(arr, key):
for i in range(len(arr)):
if arr[i] == key: return i
return -1

7a. Stack using ADT (same as 4a)


7b. Binary Search
def binary_search(arr, key):
arr.sort()
low, high = 0, len(arr)-1
while low <= high:
mid = (low + high) // 2
if arr[mid] == key: return mid
elif arr[mid] < key: low = mid + 1
else: high = mid - 1
return -1

8a. Queue using ADT (same as 5a)


8b. Merge Sort
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr)//2
L, R = arr[:mid], arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]: arr[k] = L[i]; i += 1
else: arr[k] = R[j]; j += 1
k += 1
while i < len(L): arr[k] = L[i]; i += 1; k += 1
while j < len(R): arr[k] = R[j]; j += 1; k += 1

9a. LIFO (same as Stack)


9b. Sequential Search (same as linear_search)

10a. FIFO (same as Queue)


10b. Recursive Fibonacci
def fibonacci(n):
if n <= 1: return n
return fibonacci(n-1) + fibonacci(n-2)

11. Linked List Insert/Delete


ll = LinkedList()
for val in [11, 22, 44, 55]: ll.append(val)
temp = ll.head
while temp and temp.data != 22: temp = temp.next
if temp: new_node = Node(33); new_node.next = temp.next; temp.next = new_node
prev, curr = None, ll.head
while curr and curr.data != 22:
prev = curr
curr = curr.next
if prev and curr: prev.next = curr.next
ll.display()

12a. Hash Table


hash_table = {'apple': 100, 'banana': 50}
print(hash_table)

12b. Factorial Recursive


def factorial(n):
if n == 0: return 1
return n * factorial(n-1)

13a. Tree Preorder


class TreeNode:
def __init__(self, data): self.data = data; self.left = self.right = None
def preorder(root):
if root:
print(root.data, end=' ')
preorder(root.left)
preorder(root.right)

13b. Fibonacci (same as Q10b)

14a. Tree Postorder


def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.data, end=' ')

14b. Fibonacci (same as Q10b)

15a. Tree Inorder


def inorder(root):
if root:
inorder(root.left)
print(root.data, end=' ')
inorder(root.right)

15b. Fibonacci (same as Q10b)

16a. Binary Search Tree


class BSTNode:
def __init__(self, data): self.data = data; self.left = self.right = None
def insert(root, data):
if root is None: return BSTNode(data)
if data < root.data: root.left = insert(root.left, data)
else: root.right = insert(root.right, data)
return root

16b. Selection Sort (same as Q3b)

17a. Heap
import heapq
arr = [10, 20, 15, 30, 40]
heapq.heapify(arr)
print(arr)

17b. Factorial (same as Q12b)

18a. Graph & DFS


graph = { 'A': ['B','C'], 'B': ['D'], 'C': [], 'D': [] }
def dfs(node, visited=set()):
if node not in visited:
print(node, end=" ")
visited.add(node)
for neighbour in graph[node]:
dfs(neighbour, visited)
18b. Selection Sort (same as Q3b)

19a. MST (Prim's Algorithm)


import heapq
def prims(graph, start):
visited = set()
mst = []
edges = [(0, start)]
while edges:
cost, node = heapq.heappop(edges)
if node not in visited:
visited.add(node)
mst.append((cost, node))
for to, weight in graph[node].items():
if to not in visited:
heapq.heappush(edges, (weight, to))
return mst

19b. Bubble Sort (same as Q5b)

20a. Dijkstra's Algorithm


import heapq
def dijkstra(graph, start):
pq = [(0, start)]
distances = {node: float('inf') for node in graph}
distances[start] = 0
while pq:
curr_dist, node = heapq.heappop(pq)
for neighbor, weight in graph[node].items():
distance = curr_dist + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances

20b. Factorial (same as Q12b)

You might also like