0% found this document useful (0 votes)
90 views12 pages

Python Problem

The document contains code for implementing various tree and sorting algorithms in Python. It includes code for binary search trees with functions for insertion, size calculation, and traversal. It also includes code for binary trees with breadth-first traversal, inorder, preorder and postorder traversal. Additional code implements quicksort, shellsort, queues and converting infix to postfix notation.

Uploaded by

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

Python Problem

The document contains code for implementing various tree and sorting algorithms in Python. It includes code for binary search trees with functions for insertion, size calculation, and traversal. It also includes code for binary trees with breadth-first traversal, inorder, preorder and postorder traversal. Additional code implements quicksort, shellsort, queues and converting infix to postfix notation.

Uploaded by

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

####binary search tree.

py######
class BinaryTree:
def __init__(self, data):
[Link] = data
[Link] = None
[Link] = None
def insert_left(self, new_data):
if [Link] == None:
[Link] = BinaryTree(new_data)
else:
t = BinaryTree(new_data)
[Link] = [Link]
[Link] = t
def insert_right(self, new_data):
if [Link] == None:
[Link] = BinaryTree(new_data)
else:
t = BinaryTree(new_data)
[Link] = [Link]
[Link] = t
def get_left(self):
return [Link]
def get_right(self):
return [Link]
def set_data(self,data):
[Link] = data
def get_data(self):
return [Link]
def size(my_tree):
if not my_tree:
return 0
return 1 + size(my_tree.get_left())+size(my_tree.get_right())

a = BinaryTree(1)
a.insert_left(2)
a.insert_right(3)
print(size(a))

######binary search [Link]#####


class BinaryTree:
def __init__(self, data):
[Link] = data
[Link] = None
[Link] = None
def insert_left(self, new_data):
if [Link] == None:
[Link] = BinaryTree(new_data)
else:
t = BinaryTree(new_data)
[Link] = [Link]
[Link] = t
def insert_right(self, new_data):
if [Link] == None:
[Link] = BinaryTree(new_data)
else:
t = BinaryTree(new_data)
[Link] = [Link]
[Link] = t
def get_left(self):
return [Link]
def get_right(self):
return [Link]
def set_data(self,data):
[Link] = data
def get_data(self):
return [Link]
def size(my_tree):
if not my_tree:
return 0
return 1 + size(my_tree.get_left())+size(my_tree.get_right())

a = BinaryTree(1)
a.insert_left(2)
a.insert_right(3)
print(size(a))

#####[Link] #####
class Node:

def __init__(self,info):
[Link] = info
[Link] = None
[Link] = None
[Link] = None
def __str__(self):
return str([Link])

class searchtree:
def __init__(self):
[Link] = None
def create(self,val):
if [Link] == None:
[Link] = Node(val)
else:
current = [Link]
while 1:
if val < [Link]:
if [Link]:
current = [Link]
else:
[Link] = Node(val)
break;
elif val > [Link]:
if [Link]:
current = [Link]
else:
[Link] = Node(val)
break;
else:
break

def bft(self):
[Link] = 0
queue = [[Link]]
out = []
current_level = [Link]
while len(queue) > 0:
current_node = [Link](0)
if current_node.level > current_level:
current_level += 1
[Link]("\n")
[Link](str(current_node.info) + " ")
if current_node.left:
current_node.[Link] = current_level + 1
[Link](current_node.left)
if current_node.right:
current_node.[Link] = current_level + 1
[Link](current_node.right)
result= "".join(out)
print(result)
def inorder(self,node):
if node is not None:
[Link]([Link])
print([Link])
[Link]([Link])
def preorder(self,node):
if node is not None:
print([Link])
[Link]([Link])
[Link]([Link])
def postorder(self,node):
if node is not None:
[Link]([Link])
[Link]([Link])
print([Link])
tree = searchtree()
arr = [8,3,1,6,4,7,10,14,13]
for i in arr:
[Link](i)
print('Breadth-first traversal')
[Link]()
print('Inorder Traversal')
[Link]([Link])
print('Preorder Traversal')
[Link]([Link])
print('Postorder Traversal')
[Link]([Link])

######infixto postfix#####
class Stack:
def __init__(self):
[Link] = []
def isEmpty(self):
return [Link] == []
def push(self, item):
[Link](item)
def pop(self):
return [Link]()
def peek(self):
return [Link][len([Link])-1]
def size(self):
return len([Link])
def infix_postfix(infixexp):
prec={}
prec["^"]=4
prec["*"]=3
prec["/"]=3
prec["+"]=2
prec["-"]=2
prec["("]=1
opStack=Stack()
postfixList=[]

tokenList=[Link]()
for token in tokenList:
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or \
token in "abcdefghijklmnopqrstuvwxyz" or token in "0123456789":
[Link](token)
elif token =='(':
[Link](token)
elif token == ')':
topToken = [Link]()
while topToken != '(':
[Link](topTaken)
topTaken=[Link]()
else:
while (not [Link]()) and \
(prec[[Link]()]>=prec[token]):
[Link]([Link]())
[Link](token)

while not [Link]():


[Link]([Link]())
return " ".join(postfixList)
a=infix_postfix('A + B * C - D / E * H')
print("the postfix expression of infix expression A + B * C - D / E * H is \n",a)

#######binary [Link] #######

class Node:

def __init__(self,info): #constructor of class


[Link] = info #information for node
[Link] = None #left leef
[Link] = None #right leef
[Link] = None #level none defined
def __str__(self):
return str([Link]) #return as string

class searchtree:
def __init__(self): #constructor of class
[Link] = None
def create(self,val):#create binary search tree nodes
if [Link] == None:
[Link] = Node(val)
else:
current = [Link]
while 1:
if val < [Link]:
if [Link]:
current = [Link]
else:
[Link] = Node(val)
break;
elif val > [Link]:
if [Link]:
current = [Link]
else:
[Link] = Node(val)
break;
else:
break
def bft(self): #Breadth-First Traversal
[Link] = 0
queue = [[Link]]
out = []
current_level = [Link]
while len(queue) > 0:
current_node = [Link](0)
if current_node.level > current_level:
current_level += 1
[Link]("\n")
[Link](str(current_node.info) + " ")
if current_node.left:
current_node.[Link] = current_level + 1
[Link](current_node.left)
if current_node.right:
current_node.[Link] = current_level + 1
[Link](current_node.right)
result= "".join(out)
print (result)
def inorder(self,node):
if node is not None:
[Link]([Link])
print ([Link])
[Link]([Link])
def preorder(self,node):
if node is not None:
print ([Link])
[Link]([Link])
[Link]([Link])
def postorder(self,node):
if node is not None:
[Link]([Link])
[Link]([Link])
print ([Link])

tree = searchtree()
arr = [8,3,1,6,4,7,10,14,13]
for i in arr:
[Link](i)
print ('Breadth-First Traversal')
[Link]()
print ('Inorder Traversal')
[Link]([Link])
print ('preorder Traversal')
[Link]([Link])
print ('postorder Traversal')
[Link]([Link])

#######queue#####
front=0
rear=0
mymax=eval(input("Enter maximum size of queue:"))
def createQueue():
queue=[]
return queue
def isEmpty(queue):
return len(queue)==0
def enqueue(queue,item):
[Link](item)
print("Enqueued to queue",item)
def dequeue(queue):
if isEmpty(queue):
return "Queue is Empty"
item=queue[0]
del queue[0]
return item
queue=createQueue()
while True:
print("[Link]")
print("[Link]")
print("[Link]")
print("[Link]")
ch=int(input("Enter your choice:"))
if ch==1:
if rear<mymax:
item=input("Enter any elements")
enqueue(queue,item)
rear+=1
else:
print("Queue is full")
elif ch==2:
print(dequeue(queue))
elif ch==3:
print(queue)
else:
print("Exit")
break

####quick sort####

def q_sort(a,low,high):
if low<high:
pivotpos=partition(a,low,high)
q_sort(a,low,pivotpos-1)
q_sort(a,pivotpos+1,high)

def partition(a,low,high):
pivotvalue=a[low]
up=low+1
down=high
done=False
while not done:
while up<=down and a[up]<=pivotvalue:
up+=1
while down>=up and a[down]>=pivotvalue:
down-=1
if down<up:
done=True
else:
temp=a[up]
a[up]=a[down]
a[down]=temp
temp=a[low]
a[low]=a[down]
a[down]=temp
return down

print("enter elements into list")


a=[int(x) for x in input().split()]
high=len(a)
q_sort(a,0,high-1)
print("The sorted list is",a)

####shell sort#####

def shell_sort(my_list, list_len):


interval = list_len // 2
while interval > 0:
for i in range(interval, list_len):
temp = my_list[i]
j = i
while j >= interval and my_list[j - interval] > temp:
my_list[j] = my_list[j - interval]
j -= interval
my_list[j] = temp
interval //= 2

my_list = [45, 31, 62, 12, 89, 5, 9, 8]


list_len = len(my_list)
print("the list before the sorting is:")
print(my_list)
shell_sort(my_list, list_len)
print("\nThe list after performing shell sorting is :")
print(my_list)

####selection sort#####
def s_sort(a):
for i in range(len(a)):
least=i
for k in range(i+1,len(a)):
if a[k]<a[least]:
least=k
swap(a,least,i)
def swap(a,least,i):
temp=a[least]
a[least]=a[i]
a[i]=temp

print("enter elements into list:")


a=[int(x) for x in input().split()]
s_sort(a)
print("the sorted list is",a)

#####merge sort#####
def m_sort(a):
for i in range(len(a)):
if i>1:
mid=len(a)//2
l_half=a[:mid]
r_half=a[mid:]
m_sort(l_half)
m_sort(r_half)
i=j=k=0
while i<len(l_half) and j<len(r_half):
if l_half [i]<r_half[j]:
a[k]=l_half[i]
i+=1
else:
a[k]=r_half[j]
j+=1
k+=1
while i<len(l_half):
a[k]=l_half[i]
i+=1
k+=1
while j<len(r_half):
a[k]=r_half[j]
j+=1
k+=1

print("enter elements into list:")


a=[int(x) for x in input().split()]
m_sort(a)
print("the sorted list is",a)

###### insertion sort #####


def i_sort(a):
for i in range(1,len(a)):
temp=a[i]
pos=i
while pos>0 and a[pos-1]>temp:
a[pos]=a[pos-1]
pos-=1
a[pos]=temp

print("enter elements into list:")


a=[int(x) for x in input().split()]
i_sort(a)
print("the sorted list is",a)

###heap sort####
def heapify(arr, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r

if largest != i:
arr[i],arr[largest] = arr[largest],arr[i]
heapify(arr, n, largest)

def heapsort(arr):
n = len(arr)
for i in range(n, -1, -1):
heapify(arr, n, i)

for i in range(n-1, 0, -1):


arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)

arr = [2,5,3,8,6,5,4,7]
heapsort(arr)
n = len(arr)
print("sorted array is")
for i in range(n):
print(arr[i],end=" ")

###stack#####
class Stack:
def __init__(self):
[Link] = []
def is_empty(self):
return [Link] == []
def push(self, item):
[Link](item)
def pop(self):
return [Link]()
def peek(self):
return [Link][len([Link])-1]
def size(self):
return len([Link])

s = Stack()
print(s.is_empty())
[Link](4)
[Link]('dog')
print([Link]())
[Link](True)
print([Link]())
print(s.is_empty())
[Link](8.4)
print([Link]())
print([Link]())
print([Link]())

#####stak implemenation using list####


top=0
mymax=eval(input("enter maximum size of stack"))
def createstack():
stack=[]
return stack
def isEmpty(stack):
return len(stack)==0
def push(stack,item):
[Link](item)
print("pushed to stack",item)
def pop(stack):
if isEmpty(stack):
return "stack underflow"
return [Link]()
stack=createstack()
while True:
print("[Link]")
print("[Link]")
print("[Link]")
print("[Link]")
ch=int(input("enter your choice:"))
if ch==1:
if top<mymax:
item=input("enter any elements:")
push(stack,item)
top+=1
else:
print("stack overflow")
elif ch==2:
print(pop(stack))
elif ch==3:
print(stack)
else:
print("exit")
break

####linear search #####


def l_search(a,x,l,n):
if l<=n:
mid=(l+n)//2
if a[mid]==x:
print("the element found at",l+1,"position")
else:
l_search(a,x,mid+1,n)
else:
print("element not found")

print("enter list")
a=[int(b) for b in input().split()]
x=eval(input("enter the search element"))
n=len(a)
l_search(a,x,0,n)

### fibonocci search ####


def f_search (a,x,n):
f0=0
f1=1
f2=f0+f1
while f2<n:
f0=f1
f1=f2
f2=f0+f1
offset=-1
while f2>1:
i = min(offset+f2, n-1)
if(a[i]<x):
f2=f1
f1=f0
f0=f2-f1
offset = i
elif (a[i]>x):
f2=f0
f1=f1-f2
f0=f2-f1
else:
return i
if(f1 and a[offset+f2]==x):
return offset+1
return -1

print("enter list")
a=[int(b) for b in input().split()]
[Link](a)
print("the sorted list is",a)
x=eval(input("enter the search element"))
n=len(a)
pos=f_search(a,x,n)
if pos>=0:
print("the element found at",pos+1,"position")
else:
print("element not found")

###bubble sort####
def b_sort(a):
n = len(a)
for i in range(n):
for j in range(0, n-i-1):
if a[j] > a[j+1] :
a[j], a[j+1] = a[j+1], a[j]

print("enter elements into list:")


a=[int(x) for x in input().split()]
b_sort(a)
print("the sorted list is",a)

####binary search (3)####


def b_search(a,x,l,n):
if l<=n:
mid=(l+n)//2
if a[mid]==x:
print("the element found at",mid+1,"position")
else:
if a[mid]>x:
b_search(a,x,l,mid-1)
else:
b_search(a,x,mid+1,n)
else:
print("element not found")
print("enter list")
a=[int(b) for b in input().split()]
[Link](a)
print("the sorted list is",a)
x=eval(input("enter the search element"))
n=len(a)
b_search(a,x,0,n)

##### sequential search ######


def sequentialsearch(dlist, item):
pos=0
found=False

while pos<len(dlist) and not found:


if dlist[pos]==item:
found=True
else:
pos=pos+1
return found,pos
test_list=[1,2,3,4,5,6,7,8]
print(sequentialsearch(test_list,2))
print(sequentialsearch(test_list,8))

You might also like