IMPLEMENT SIMPLE ADTS AS PYTHON CLASSES
1)a. Stack
stack=[]
#append() functionto push
#element in the stack
[Link]('a')
[Link]('b')
[Link]('c')
print('initial stack')
print(stack)
#element from stack in
#LIFO order
print('\n Elements popped from stack:')
print([Link]())
print([Link]())
print([Link]())
print('\n stack after elements are popped:')
print(stack)
Output:
initial stack
['a', 'b', 'c']
Elements popped from stack:
C
b
a
stack after elements are popped:
[]
1)b. Queue
queue=[]
print('Before Enqueue,Its Empty')
print(queue)
queue=["A","B","C"]
print('After enqueue,The queue is')
print(queue)
print('Now Enqueue or Insertion')
[Link]("D")
[Link]("E")
print(queue)
print ('After Deletion,Dequeue')
print([Link](0))
print(queue)
print([Link](0))
print(queue)
print([Link](0))
print(queue)
print([Link](0))
print(queue)
Output:
Before Enqueue,Its Empty
[]
After enqueue,The queue is
['A', 'B', 'C']
Now Enqueue or Insertion
['A', 'B', 'C', 'D', 'E']
After Deletion,Dequeue
A
['B', 'C', 'D', 'E']
B
['C', 'D', 'E']
C
['D', 'E']
D
['E']
1)c. Flower constructor
class flower:
def __init__(self,txt):
print(txt,"I am in flower class")
class jasmine(flower):
def __init__(self,txt):
print(txt,"I am in Jasmine class")
super().__init__(txt)
class rose(jasmine):
def __init__(self,txt):
print(txt,"I am in Rose class")
super().__init__(txt)
class lilly(rose):
def __init__(self,txt):
print(txt,"I am in lilly class")
super().__init__(txt)
class tulip(lilly,rose):
def __init__(self,txt):
print(txt,"I am in tulip class ")
super().__init__("final Derived")
d=tulip("It is tulip")
h=rose("I am Rose")
Output:
It is tulip I am in tulip class
final Derived I am in lilly class
final Derived I am in Rose class
final Derived I am in Jasmine class
final Derived I am in flower class
I am Rose I am in Rose class
I am Rose I am in Jasmine class
I am Rose I am in flower class
IMPLEMENT RECURSIVE ALGORITHMS IN PYTHON
2)a. Factorial
num=7
factorial=1
if num<0:
print("Sorry,factorial does not exist for negative numbers")
elif num==0:
print("The factorial of 0 is 1")
else:
for i in range(1,num+1):
factorial=factorial*i
print("The factorial of",num,"is",factorial)
Output:
The factorial of 7 is 5040
2)b. Fibonacci series
def recur_fibo(n):
if n<=1:
return n
else:
return(recur_fibo(n-1)+recur_fibo(n-2))
nterms=10
if nterms<=0:
print("Please enter a positive interger")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Output:
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
2)c. Binary Search
def binary_search(arr,low,high,x):
if high>=low:
mid=(high+low)//2
if arr[mid]==x:
return mid
elif arr[mid]>x:
return binary_search(arr,low,mid-1,x)
else:
return binary_search(arr,mid+1,high,x)
else:
return-1
arr=[2,3,4,10,40]
x=10
result=binary_search(arr,0,len(arr)-1,x)
if result!=-1:
print("Element is present at index",str(result))
else:
print("Element is not present in array")
Output:
Element is present at index 3
3. IMPLEMENT LIST ADT USING PYTHON ARRAYS
import array as arr
a=[Link]('i',[1,2,3])
print("Array before insertion:",end=" ")
for i in range(0,3):
print(a[i],end=" ")
print()
[Link](1,4)
print("Array after insertion:",end=" ")
for i in (a):
print(i,end=" ")
print()
[Link](5)
print("Array after insertion at end:",end=" ")
for i in (a):
print(i,end=" ")
print()
[Link](5)
print("Array after Deletion:",end=" ")
for i in (a):
print(i,end=" ")
print()
x=[Link](4)
print("Value 4 is present in location")
print(x)
Output:
Array before insertion: 1 2 3
Array after insertion: 1 4 2 3
Array after insertion at end: 1 4 2 3 5
Array after Deletion: 1 4 2 3
Value 4 is present in location
1
4. IMPLEMENT OF LINKED LIST USING PYTHON LIST
class Node:
def __init__(self,dataval=None):
[Link]=dataval
[Link]=None
class slinkedlist:
def __init__(self):
[Link]=None
[Link]=None
def atend(self,newdata):
newnode=Node(newdata)
if [Link] is None:
[Link]=newnode
return
last=[Link]
while([Link]):
last=[Link]
[Link]=newnode
def listprint(self):
printval=[Link]
while printval is not None:
print([Link])
printval =[Link]
def inbetween(self,middle_node,newdata):
if middle_node is None:
print("The mentioned node is absent")
return
newnode=node(newdata)
[Link]=middle_node.nextval
middle_node.nextval=newnode
def removenode(self,removekey):
head=[Link]
if([Link] is not None):
if([Link]==removekey):
[Link]=[Link]
head=None
return
prev=None
while(head is not None):
if [Link]==removekey:
break
prev=head
head=[Link]
if (head==None):
return
[Link]=[Link]
head=None
list = slinkedlist()
[Link]("Monday")
[Link]("Tuesday")
[Link]("Wednesday")
[Link]()
[Link]("Thursday")
[Link]()
l2=[Link]
[Link](l2,"Friday")
[Link]()
[Link]("Tuesday")
[Link]()
Output:
Monday
Tuesday
Wednesday
Monday
Tuesday
Wednesday
Thursday
Monday
Tuesday
Wednesday
Thursday
Monday
Wednesday
Thursday
5. IMPLEMENTATION OF STACK AND QUEUE ADTS
5a. Stack using array
class stackusingarray:
def __init__(self):
[Link]=[]
def push(self,element):
[Link](element)
def pop(self):
if(not [Link]()):
lastelement=[Link][-1]
del([Link][-1])
return lastelement
else:
return("Stack already Empty")
def isEmpty(self):
return [Link]==[]
def printstack(self):
print([Link])
if __name__=="__main__":
s=stackusingarray()
print("*"*5+"Stack Using Array"+5*"*")
while(True):
print("Enter Your Choice:")
el=int(input("1 for push \n 2 for pop \n 3 to check if it is Empty \n 4 to print stack \n 5 to exit \n"))
if(el==1):
item=input("Enter Element to push in stack\n")
[Link](item)
if(el==2):
print("Popped Element is")
print([Link]())
if(el==3):
print([Link]())
if(el==4):
[Link]()
if(el==5):
break
Output:
*****Stack Using Array*****
Enter Your Choice:
1 for push
2 for pop
3 to check if it is Empty
4 to print stack
5 to exit
1
Enter Element to push in stack
4
Enter Your Choice:
1 for push
2 for pop
3 to check if it is Empty
4 to print stack
5 to exit
1
Enter Element to push in stack
7
Enter Your Choice:
1 for push
2 for pop
3 to check if it is Empty
4 to print stack
5 to exit
2
Popped Element is
7
Enter Your Choice:
1 for push
2 for pop
3 to check if it is Empty
4 to print stack
5 to exit
2
Popped Element is
4
Enter Your Choice:
1 for push
2 for pop
3 to check if it is Empty
4 to print stack
5 to exit
2
Popped Element is
Stack already Empty
Enter Your Choice:
1 for push
2 for pop
3 to check if it is Empty
4 to print stack
5 to exit
5
b. Queue using array
class queue:
def __init__(self):
[Link]=[]
def is_Empty(self):
return [Link]==[]
def enqueue(self,data):
[Link](data)
def dequeue(self):
return [Link](0)
q=queue()
while True:
print('enqueue<value>')
print('dequeue')
print('quit')
do=input("what would you like to do?").split()
operation=do[0].strip().lower()
if operation=='enqueue':
[Link](int(do[1]))
elif operation=='dequeue':
if q.is_Empty():
print('queue isEmpty:')
else:
print('dequeued value:',[Link]())
elif operation=='quit':
break
Output:
enqueue<value>
dequeue
quit
what would you like to do?enqueue 90
enqueue<value>
dequeue
quit
what would you like to do?enqueue 45
enqueue<value>
dequeue
quit
what would you like to do?dequeue
dequeued value: 90
enqueue<value>
dequeue
quit
what would you like to do?dequeue
dequeued value: 45
enqueue<value>
dequeue
quit
what would you like to do?dequeue
queue isEmpty:
enqueue<value>
dequeue
quit
what would you like to do?quit
5c. Stack using linkedlist
class Node:
def __init__(self,data):
[Link]=data
[Link]=None
class stack:
def __init__(self):
[Link]=None
def push(self,data):
if [Link] is None:
[Link]=Node(data)
else:
new_node=Node(data)
new_node.next=[Link]
[Link]=new_node
def pop(self):
if [Link] is None:
return None
else:
popped=[Link]
[Link]=[Link]
return popped
a_stack=stack()
while True:
print('push<value>')
print('pop')
print('quit')
do=input('what would you lke to do?').split()
operation=do[0].strip().lower()
if operation=='push':
a_stack.push(int(do[1]))
elif operation=='pop':
popped=a_stack.pop()
if popped is None:
print('stack is empty.')
else:
print('popped value:',int(popped))
elif operation=='quit':
break
Output:
push<value>
pop
quit
what would you lke to do?pop
stack is empty.
push<value>
pop
quit
what would you lke to do?push 5
push<value>
pop
quit
what would you lke to do?push 8
push<value>
pop
quit
what would you lke to do?pop
popped value: 8
push<value>
pop
quit
what would you lke to do?pop
popped value: 5
push<value>
pop
quit
what would you lke to do?pop
stack is empty.
push<value>
pop
quit
what would you lke to do?quit
5d. Queue using linkedlist
class Node:
def __init__(self, data):
[Link] = data
[Link] = None
class Queue:
def __init__(self):
[Link] = None
[Link] = None
def enqueue(self, data):
if [Link] is None:
[Link] = Node(data)
[Link] = [Link]
else:
[Link] = Node(data)
[Link] = [Link]
def dequeue(self):
if [Link] is None:
return None
else:
to_return = [Link]
[Link] = [Link]
return to_return
a_queue=Queue()
while True:
print("enqueue <value>")
print("dequeue")
print("quit")
do=input("What would you like to do?").split()
operation=do[0].strip().lower()
if operation=='enqueue':
a_queue.enqueue(int(do[1]))
elif operation=='dequeue':
dequeued=a_queue.dequeue()
if dequeued is None:
print('Queue is empty.')
else:
print('Dequeued element:',int(dequeued))
elif operation=='quit':
break
Output:
enqueue <value>
dequeue
quit
What would you like to do?enqueue 4
enqueue <value>
dequeue
quit
What would you like to do?enqueue 9
enqueue <value>
dequeue
quit
What would you like to do?dequeue
Dequeued element: 4
enqueue <value>
dequeue
quit
What would you like to do?dequeue
Dequeued element: 9
enqueue <value>
dequeue
quit
What would you like to do?dequeue
Queue is empty.
enqueue <value>
dequeue
quit
What would you like to do?quit
6. APPLICATION OF STACK
6a. Postfix Evaluation
operators=set(['*','-','+','%','/','**'])
def evaluate_postfix(expression):
stack=[]
for i in expression:
if i not in operators:
[Link](i)
else:
a=[Link]()
b=[Link]()
if i=='+':
res=int(b)+int(a)
elif i=='-':
res=int(b)-int(a)
elif i=='*':
res=int(b)*int(a)
elif i=='%':
res=int(b)%int(a)
elif i=='/':
res=int(b)/int(a)
elif i=='**':
res=int(b)**int(a)
[Link](res)
return(''.join(map(str,stack)))
expression=input("Enter the postfix expressions:")
print()
print("postfix expression entered:",expression)
print("evaluation result:",evaluate_postfix(expression))
Output:
Enter the postfix expressions:634*+2-
postfix expression entered: 634*+2-
evaluation result: 16
6b. Application of Queue ADT
print("FIRST COME FIRST SERVE SCHEDULLING")
n=int(input("Enter number of processes:"))
d=dict()
for i in range(n):
key="p"+str(i+i)
a=int(input("Enter arival time of process"+str(i+1)+":"))
b=int(input("Enter burst time of process"+str(i+1)+":"))
l=[]
[Link](a)
[Link](b)
d[key]=l
d=sorted([Link](),key=lambda item: item[1][0])
ET=[]
for i in range(len(d)):
if(i==0):
[Link](d[i][1][1])
else:
[Link](ET[i-1]+d[i][1][1])
TAT=[]
for i in range(len(d)):
[Link](ET[i]-d[i][1][0])
WT=[]
for i in range(len(d)):
[Link](TAT[i]-d[i][1][1])
avg_WT=0
for i in WT:
avg_WT+=i
avg_WT=(avg_WT/n)
print("process|arrival|burst|exit|turn around|wait|")
for i in range(n):
print("",d[i][0],"|",d[i][0],"|",d[i][1][1],"|",ET[i],"|",TAT[i],"|",WT[i],"|")
print("Average waiting Time:",avg_WT)
Output:
FIRST COME FIRST SERVE SCHEDULLING
Enter number of processes:3
Enter arival time of process1:1
Enter burst time of process1:4
Enter arival time of process2:0
Enter burst time of process2:3
Enter arival time of process3:2
Enter burst time of process3:5
process|arrival|burst|exit|turn around|wait|
p2 | p2 | 3 | 3 | 3 | 0 |
p0 | p0 | 4 | 7 | 6 | 2 |
p4 | p4 | 5 | 12 | 10 | 5 |
Average waiting Time: 2.3333333333333335
7a. Linear Search
def linear_search(list1,n,key):
for i in range(0,n):
if(list1[i]==key):
return i
return -1
list1=[1,3,5,4,7,9]
key=7
n=len(list1)
res=linear_search(list1,n,key)
if(res==-1):
print("Elements not found")
else:
print("Element found at index:",res)
Output:
Element found at index: 4
7b. Binary Search
def binary_search(list1,n):
low=0
high=len(list1)-1
mid=0
while low<=high:
mid=(high+low)//2
if list1[mid]<n:
low=mid+1
elif list1[mid]>n:
high=mid-1
else:
return mid
return -1
list1=[12,24,32,39,45,50,54]
print(list1)
n=int(input("Enter the element to be searched:"))
result=binary_search(list1,n)
if result!=-1:
print("Element is present at index",str(result))
else:
print("Element is not present in list1")
Output:
[12, 24, 32, 39, 45, 50, 54]
Enter the element to be searched:45
Element is present at index 4
7c. Bubble sort
def bubble_sort(list1):
for i in range(0,len(list1)-1):
for j in range(len(list1)-1):
if(list1[j]>list1[j+1]):
temp=list1[j]
list1[j]=list1[j+1]
list1[j+1]=temp
return list1
list1=[5,3,8,6,7,2]
print("The unsorted list is:",list1)
print("The sorted list is:",bubble_sort(list1))
Output:
The unsorted list is: [5, 3, 8, 6, 7, 2]
The sorted list is: [2, 3, 5, 6, 7, 8]
7d. Insertion sort
def insertionsort(arr):
n=len(arr)
if n<=1:
return
for i in range(1,n):
key=arr[i]
j=i-1
while j>=0 and key<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=key
arr=[12,11,13,5,6]
print("before sorting")
print(arr)
insertionsort(arr)
print("Ascending order is")
print(arr)
Output:
before sorting
[12, 11, 13, 5, 6]
Ascending order is
[5, 6, 11, 12, 13]
7e. Selection Sort
def selectionsort(array,size):
for ind in range(size):
min_index=ind
for j in range(ind +1,size):
if array[j]<array[min_index]:
min_index=j
(array[ind],array[min_index])=(array[min_index],array[ind])
arr=[-2,45,0,11,-9,88,-97,-202,747]
size=len(arr)
selectionsort(arr,size)
print("The array after sorting in ascending order by selection sort:")
print(arr)
Output:
The array after sorting in ascending order by selection sort:
[-202, -97, -9, -2, 0, 11, 45, 88, 747]
7f. Quick Sort
def quicksort(arr):
if len(arr)<=1:
return arr
else:
pivot=arr[0]
left=[x for x in arr[1:]if x<pivot]
right=[x for x in arr[1:]if x>=pivot]
return quicksort(left)+[pivot]+quicksort(right)
user_input=input("Enter the array elements seperated by spaces:")
arr=[int(x)for x in user_input.split()]
sorted_arr=quicksort(arr)
print("sorted array:",sorted_arr)
Output:
Enter the array elements seperated by spaces:78 12 5 98 46 73 23
sorted array: [5, 12, 23, 46, 73, 78, 98]
8. Implementation of Hash Table
class Node:
def __init__(self, key, value):
[Link] = key
[Link] = value
[Link] = None
class HashTable:
def __init__(self, capacity):
[Link] = capacity
[Link] = 0
[Link] = [None] * capacity
def hash(self, key):
return hash(key) % [Link]
#Insert
def insert(self, key, value):
index = [Link](key)
if [Link][index] is None:
[Link][index] = Node(key, value)
[Link] += 1
else:
current = [Link][index]
while current:
if [Link] == key:
[Link] = value
return
current = [Link]
new_node = Node(key, value)
new_node=[Link][index]
[Link][index]=new_node
[Link] += 1
#Search
def search(self, key):
index = [Link](key)
current = [Link][index]
while current:
if [Link] == key:
return [Link]
current = [Link]
raise KeyError(key)
#Remove
def remove(self, key):
index = [Link](key)
previous = None
current = [Link][index]
while current:
if [Link] == key:
if previous:
[Link] = [Link]
else:
[Link][index] = [Link]
[Link] -= 1
return
previous = current
current = [Link]
raise KeyError(key)
def __len__(self):
return [Link]
def __contains__(self, key):
try:
[Link](key)
return True
except KeyError:
return False
if __name__ == '__main__':
ht = HashTable(5)
[Link]("apple", 3)
[Link]("banana", 2)
[Link]("cherry", 5)
print("apple" in ht)
print("durian" in ht)
print([Link]("banana"))
[Link]("banana", 4)
print([Link]("banana"))
[Link]("apple")
print(len(ht))
Output:
True
False
2
4
2
9. Tree Traversal and Traversal Algorithms
class Node:
def __init__(self, data):
[Link] = None
[Link] =None
[Link] =data
def insert(self, data):
if [Link]:
if data < [Link]:
if [Link] is None:
[Link] = Node(data)
else:
[Link](data)
elif data > [Link]:
if [Link] is None:
[Link] = Node(data)
else:
[Link](data)
else:
[Link] = data
def PrintTree(self):
if [Link]:
[Link]()
print([Link])
if [Link]:
[Link]()
def inorderTraversal(self, root):
res = []
if root:
res = [Link]([Link])
[Link]([Link])
res = res + [Link]([Link])
return res
def preorderTraversal(self, root):
res = []
if root:
[Link]([Link])
res = res + [Link]([Link])
res = res + [Link]([Link])
return res
def postorderTraversal(self, root):
res = []
if root:
res = [Link]([Link])
res = res + [Link]([Link])
[Link]([Link])
return res
root = Node(27)
[Link](14)
[Link](35)
[Link](10)
[Link](19)
[Link](31)
[Link](42)
print('Inorder Traversal')
print([Link](root))
print('Preorder Traversal')
print([Link](root))
print('Postorder Traversal')
print([Link](root))
Output:
Inorder Traversal
[10, 14, 19, 27, 31, 35, 42]
Preorder Traversal
[27, 14, 10, 19, 35, 31, 42]
Postorder Traversal
[10, 19, 14, 31, 42, 35, 27]
10. Implemetation of Binary Search Tree
class Node:
def __init__(self, key):
[Link] = key
[Link] = None
[Link] = None
def inorder(root):
if root is not None:
inorder([Link])
print(str([Link]) + "->", end=' ')
inorder([Link])
def insert(node, key):
if node is None:
return Node(key)
if key < [Link]:
[Link] = insert([Link], key)
else:
[Link] = insert([Link], key)
return node
def minValueNode(node):
current = node
while([Link] is not None):
current = [Link]
return current
def maxValueNode(node):
current=node
while([Link] is not None):
current=[Link]
return current
def search(root,value):
if root==None:
return False
elif [Link]==value:
return True
elif [Link]<value:
return search([Link],value)
else:
return search([Link],value)
def deleteNode(root, key):
if root is None:
return root
if key < [Link]:
[Link] = deleteNode([Link], key)
elif(key > [Link]):
[Link] = deleteNode([Link], key)
else:
if [Link] is None:
temp = [Link]
root = None
return temp
elif [Link] is None:
temp = [Link]
root = None
return temp
temp = minValueNode([Link])
[Link] = [Link]
[Link] = deleteNode([Link], [Link])
return root
root = None
root = insert(root, 8)
root = insert(root, 3)
root = insert(root, 1)
root = insert(root, 6)
root = insert(root, 7)
root = insert(root, 10)
root = insert(root, 14)
root = insert(root, 4)
print("Inorder traversal: ", end=' ')
inorder(root)
print("\nDelete 10")
root = deleteNode(root, 10)
print("Inorder traversal: ", end=' ')
inorder(root)
print("\nMinimum Value")
temp=minValueNode(root)
print([Link])
print("\nMaximum Value")
temp=maxValueNode(root)
print([Link])
print('Searching 14')
print(search(root,14))
print('Searching 22')
print(search(root,22))
Output:
Inorder traversal: 1-> 3-> 4-> 6-> 7-> 8-> 10-> 14->
Delete 10
Inorder traversal: 1-> 3-> 4-> 6-> 7-> 8-> 14->
Minimum Value: 1
Maximum Value: 14
Searching 14: True
Searching 22: False
[Link] of Heaps
def min_heapify(A,k):
l=left(k)
r=right(k)
if l<len(A) and A[l]<A[k]:
smallest=l
else:
smallest=k
if r<len(A) and A[r]<A[smallest]:
smallest=r
if smallest!=k:
A[k],A[smallest]=A[smallest],A[k]
min_heapify(A,smallest)
def left(k):
return 2*k+1
def right(k):
return 2*k+2
def build_min_heap(A):
n=int((len(A)//2)-1)
for k in range(n,-1,-1):
min_heapify(A,k)
A=[3,9,2,1,4,5]
build_min_heap(A)
print(A)
Output:
[1, 3, 2, 9, 4, 5]
12. Python Program To Implement Breadth First Search
[Link]
graph={
'A':['B','C'],
'B':['D','E'],
'C':['F'],
'D':[],
'E':['F'],
'F':[]
}
visited=[]
queue=[]
def bfs(visited,graph,node):
[Link](node)
[Link](node)
while queue:
s=[Link](0)
print(s,end=" ")
for neighbour in graph[s]:
if neighbour not in visited:
[Link](neighbour)
[Link](neighbour)
bfs(visited,graph,'A')
Output:
A B C D E F
[Link]
graph={
'A':['B','c'],
'B':['D','E'],
'c':['F'],
'D':[],
'E':['F'],
'F':[]
}
visited=set()
def dfs(visited,graph,node):
if node not in visited:
print(node)
[Link](node)
for neighbour in graph[node]:
dfs(visited,graph,neighbour)
dfs(visited,graph,'A')
Output:
A
B
D
E
F
C
13. Implementation of Single Source Shortest Path Algorithm
class Graph:
def __init__(self, vertices):
self.V = vertices
[Link] = [[0 for _ in range(vertices)] for _ in range(vertices)]
def print_solution(self, dist):
print("Vertex \t Distance from Source")
for node in range(self.V):
print(node, "\t", dist[node])
def min_distance(self, dist, spt_set):
min_distance = float('inf')
min_index = -1
for v in range(self.V):
if dist[v] < min_distance and not spt_set[v]:
min_distance = dist[v]
min_index = v
return min_index
def dijkstra(self, src):
dist = [float('inf')] * self.V
dist[src] = 0
spt_set = [False] * self.V
for _ in range(self.V):
u = self.min_distance(dist, spt_set)
spt_set[u] = True
for v in range(self.V):
if ([Link][u][v] > 0 and
not spt_set[v] and
dist[v] > dist[u] + [Link][u][v]):
dist[v] = dist[u] + [Link][u][v]
self.print_solution(dist)
# Create a graph instance
g = Graph(9)
[Link] = [
[0, 4, 0, 0, 0, 0, 8, 0, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]
[Link](0)
Output:
Vertex Distance from Source
0 0
1 4
2 12
3 19
4 20
5 10
6 8
7 9
8 14
[Link] of Minimum Spanning Tree Algorithms
14a. Prim’s Algorithm
INF=99999
N=5
G=[[0,19,5,0,0],
[19,0,5,9,2],
[5,5,0,1,6],
[0,9,1,0,1],
[0,2,6,1,0]]
selected_node=[False]*N
no_edge=0
selected_node[0]=True
print("edge:weight \n")
while(no_edge<N-1):
minimum=INF
a=0
b=0
for m in range(N):
if selected_node[m]:
for n in range(N):
if((not selected_node[n])and G[m][n]):
if minimum>G[m][n]:
minimum=G[m][n]
a=m
b=n
print(str(a)+"_"+str(b)+":"+str(G[a][b]))
selected_node[b]= True
no_edge+=1
Output:
Edge : weight
0_2 : 5
2_3 : 1
3_4 : 1
4_1 : 2
14b. Kruska’s Algorithm
class Graph:
def __init__(self, vertices):
self.V = vertices
[Link] = []
def add_edge(self, u, v, w):
[Link]([u, v, w])
def find(self, parent, i):
if parent[i] == i:
return i
return [Link](parent, parent[i])
def apply_union(self, parent, rank, x, y):
xroot = [Link](parent, x)
yroot = [Link](parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def kruskal_algo(self):
result = []
i, e = 0, 0
[Link] = sorted([Link], key=lambda item: item[2])
parent = []
rank = []
for node in range(self.V):
[Link](node)
[Link](0)
while e < self.V - 1:
u, v, w = [Link][i]
i=i+1
x = [Link](parent, u)
y = [Link](parent, v)
if x != y:
e=e+1
[Link]([u, v, w])
self.apply_union(parent, rank, x, y)
for u, v, weight in result:
print("%d - %d: %d" % (u, v, weight))
g = Graph(6)
g.add_edge(0, 1, 4)
g.add_edge(0, 2, 4)
g.add_edge(1, 2, 2)
g.add_edge(1, 0, 4)
g.add_edge(2, 0, 4)
g.add_edge(2, 1, 2)
g.add_edge(2, 3, 3)
g.add_edge(2, 5, 2)
g.add_edge(2, 4, 4)
g.add_edge(3, 2, 3)
g.add_edge(3, 4, 3)
g.add_edge(4, 2, 4)
g.add_edge(4, 3, 3)
g.add_edge(5, 2, 2)
g.add_edge(5, 4, 3)
g.kruskal_algo()
Output:
1–2 : 2
2–5 : 2
2–3 : 3
3–4 : 3
0–1 : 4
15. Implementation of AVL Tree Algorithm
class treeNode(object):
def __init__(self, value):
[Link] = value
self.l = None
self.r = None
self.h = 1
class AVLTree(object):
def insert(self, root, key):
if not root:
return treeNode(key)
elif key < [Link]:
root.l = [Link](root.l, key)
else:
root.r = [Link](root.r, key)
root.h = 1 + max([Link](root.l), [Link](root.r))
b = [Link](root)
if b > 1 and key < [Link]:
return [Link](root)
if b < -1 and key > [Link]:
return [Link](root)
if b > 1 and key > [Link]:
root.l = [Link](root.l)
return [Link](root)
if b < -1 and key < [Link]:
root.r = [Link](root.r)
return [Link](root)
return root
def lRotate(self, z):
y = z.r
T2 = y.l
y.l = z
z.r = T2
z.h = 1 + max([Link](z.l), [Link](z.r))
y.h = 1 + max([Link](y.l), [Link](y.r))
return y
def rRotate(self, z):
y = z.l
T3 = y.r
y.r = z
z.l = T3
z.h = 1 + max([Link](z.l), [Link](z.r))
y.h = 1 + max([Link](y.l), [Link](y.r))
return y
def getHeight(self, root):
if not root:
return 0
return root.h
def getBal(self, root):
if not root:
return 0
return [Link](root.l) - [Link](root.r)
def preOrder(self, root):
if not root:
return
print("{0}".format([Link]), end="")
[Link](root.l)
[Link](root.r)
# Driver code
Tree = AVLTree()
root = None
root = [Link](root, 1)
root = [Link](root, 2)
root = [Link](root, 3)
root = [Link](root, 4)
root = [Link](root, 5)
root = [Link](root, 6)
print("PreOrder traversal of the constructed AVL tree is:")
[Link](root)
print()
Output:
PreOrder traversal of the constructed AVL tree is:
4 2 1 3 5 6