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

Data Structure with Python

The document contains implementations of various data structures including Stack, Queue, Circular Queue, Priority Queue, and Single Linked List, along with their respective operations. It provides a main menu interface for user interaction to perform operations like push, pop, enqueue, dequeue, and display elements. Additionally, it includes algorithms for infix to postfix conversion and postfix evaluation.

Uploaded by

tiyasha2950
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)
3 views

Data Structure with Python

The document contains implementations of various data structures including Stack, Queue, Circular Queue, Priority Queue, and Single Linked List, along with their respective operations. It provides a main menu interface for user interaction to perform operations like push, pop, enqueue, dequeue, and display elements. Additionally, it includes algorithms for infix to postfix conversion and postfix evaluation.

Uploaded by

tiyasha2950
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/ 1

Stack

In [1]:
class stack:
def __init__(self,values):
self.values=list()
def push(self,element):
return self.values.append(element)
def pop(self):
if not (self.isEmpty()):
self.values.pop()
else:
print("Stack is Empty")
def top(self):
return self.values[-1]
def isEmpty(self):
return len(self.values)==0
def size(self):
return len(self.values)
def display(self):
print("The stack is: ",self.values)
#MAIN PROGRAM
st=stack([])
while True:
print("\n***MAIN MENU***\n1. PUSH\n2. POP\n3. EMPTY CHECK\n4. SIZE OF THE STACK\n5. DISPLAY\n6. TOP\n7. EXIT")
choice=int(input("Enter your choice:"))
if(choice==1):
element=input("Enter a element:")
st.push(element)
elif(choice==2):
val=st.top()
st.pop()
print("Popped element is:",val)
elif(choice==3):
check=st.isEmpty()
if(check==True):
print("Stack is empty")
else:
print("Stack is not empty")
elif(choice==4):
print("The size of the stack is: ",st.size())
elif(choice==5):
st.display()
elif(choice==6):
print("The top of the stack is:",st.top())
elif(choice==7):
break
else:
print("Enter a valid choice")

***MAIN MENU***
1. PUSH
2. POP
3. EMPTY CHECK
4. SIZE OF THE STACK
5. DISPLAY
6. TOP
7. EXIT
Enter your choice:1
Enter a element:10

***MAIN MENU***
1. PUSH
2. POP
3. EMPTY CHECK
4. SIZE OF THE STACK
5. DISPLAY
6. TOP
7. EXIT
Enter your choice:1
Enter a element:20

***MAIN MENU***
1. PUSH
2. POP
3. EMPTY CHECK
4. SIZE OF THE STACK
5. DISPLAY
6. TOP
7. EXIT
Enter your choice:1
Enter a element:30

***MAIN MENU***
1. PUSH
2. POP
3. EMPTY CHECK
4. SIZE OF THE STACK
5. DISPLAY
6. TOP
7. EXIT
Enter your choice:2
Popped element is: 30

***MAIN MENU***
1. PUSH
2. POP
3. EMPTY CHECK
4. SIZE OF THE STACK
5. DISPLAY
6. TOP
7. EXIT
Enter your choice:6
The top of the stack is: 20

***MAIN MENU***
1. PUSH
2. POP
3. EMPTY CHECK
4. SIZE OF THE STACK
5. DISPLAY
6. TOP
7. EXIT
Enter your choice:5
The stack is: ['10', '20']

***MAIN MENU***
1. PUSH
2. POP
3. EMPTY CHECK
4. SIZE OF THE STACK
5. DISPLAY
6. TOP
7. EXIT
Enter your choice:4
The size of the stack is: 2

***MAIN MENU***
1. PUSH
2. POP
3. EMPTY CHECK
4. SIZE OF THE STACK
5. DISPLAY
6. TOP
7. EXIT
Enter your choice:7

Infix to Postfix Evaluation


In [3]:
def isOperator(ch):
return (ch == '+' or ch == '-' or ch == '*' or ch == '/' or ch == '%' or ch == '^')

def getPrecedence(op):
if op=='^':
return 3
elif(op=='*' or op=='/' or op=='%'):
return 2
elif(op=='+' or op=='-'):
return 1
else:
return -1

infix = input("Enter the infix expression: ")


postfix = ''
stack = []

for i in infix:
if i.isalnum():
postfix+=i
elif i=='(':
stack.append(i)
elif i==')':
while (len(stack)!=0 and stack[-1]!='('):
postfix+=stack.pop()
if (len(stack)!=0 and stack[-1]=='('):
stack.pop()
elif isOperator(i):
while(len(stack)!=0 and getPrecedence(i)<=getPrecedence(stack[-1])):
postfix+=stack.pop()
stack.append(i)

while(len(stack)!=0):
postfix+=stack.pop()

print("The postfix expression is: ",postfix)

Enter the infix expression: ((A+B)-C*(D/E))+F


The postfix expression is: AB+CDE/*-F+

Postfix Evaluation
In [38]:
class Postfix:
def __init__(self):
self.operators=['+','-','*','/','^']
self.stack=[]

def evaluate(self,expression):
expression=expression.split(' ')
for ch in expression:
if ch not in self.operators:
self.stack.append(ch)
else:
num2=self.stack.pop()
num1=self.stack.pop()
result=self.operation(ch,num1,num2)
self.stack.append(result)
return self.stack.pop()

def operation(self,operator,num1,num2):
num1=float(num1)
num2=float(num2)
if operator=='+':
return num1+num2
if operator=='-':
return num1-num2
if operator=='*':
return num1*num2
if operator=='/':
return num1/num2
if operator=='^':
return num1**num2
else:
raise ValueError("Invalid!")

evaluator=Postfix()
exp=input('Enter the Postfix Expression:')
result=evaluator.evaluate(exp)
print('Answer is:',result)

Enter the Postfix Expression:2 3 1 * + 9 -


Answer is: -4.0

Queue
In [2]:
class Queue:
def __init__(self,values):
self.values=list()
def enqueue(self,element):
return self.values.append(element)
def dequeue(self):
if self.isEmpty():
print("Queue Underflow")
else:
return self.values.pop(0)
def isEmpty(self):
return len(self.values)==0
def display(self):
return self.values
def size(self):
return len(self.values)
qu=Queue([])
while True:
print("\n***MAIN MENU***\n1. ENQUEUE\n2. DEQUEUE\n3. EMPTY CHECK\n4. SIZE OF THE QUEUE\n5. DISPLAY\n6. EXIT")
choice=int(input("Enter your choice:"))
if(choice==1):
element=input("Enter a element:")
qu.enqueue(element)
elif(choice==2):
val=qu.values[0]
qu.dequeue()
print("Dequeued element is:",val)
elif(choice==3):
check=qu.isEmpty()
if(check==True):
print("Queue is empty")
else:
print("Queue is not empty")
elif(choice==4):
print("The size of the queue is: ",qu.size())
elif(choice==5):
print("The queue is:",qu.display())
elif(choice==6):
break
else:
print("Enter a valid choice")

***MAIN MENU***
1. ENQUEUE
2. DEQUEUE
3. EMPTY CHECK
4. SIZE OF THE QUEUE
5. DISPLAY
6. EXIT
Enter your choice:1
Enter a element:14

***MAIN MENU***
1. ENQUEUE
2. DEQUEUE
3. EMPTY CHECK
4. SIZE OF THE QUEUE
5. DISPLAY
6. EXIT
Enter your choice:1
Enter a element:28

***MAIN MENU***
1. ENQUEUE
2. DEQUEUE
3. EMPTY CHECK
4. SIZE OF THE QUEUE
5. DISPLAY
6. EXIT
Enter your choice:1
Enter a element:64

***MAIN MENU***
1. ENQUEUE
2. DEQUEUE
3. EMPTY CHECK
4. SIZE OF THE QUEUE
5. DISPLAY
6. EXIT
Enter your choice:5
The queue is: ['14', '28', '64']

***MAIN MENU***
1. ENQUEUE
2. DEQUEUE
3. EMPTY CHECK
4. SIZE OF THE QUEUE
5. DISPLAY
6. EXIT
Enter your choice:2
Dequeued element is: 14

***MAIN MENU***
1. ENQUEUE
2. DEQUEUE
3. EMPTY CHECK
4. SIZE OF THE QUEUE
5. DISPLAY
6. EXIT
Enter your choice:5
The queue is: ['28', '64']

***MAIN MENU***
1. ENQUEUE
2. DEQUEUE
3. EMPTY CHECK
4. SIZE OF THE QUEUE
5. DISPLAY
6. EXIT
Enter your choice:4
The size of the queue is: 2

***MAIN MENU***
1. ENQUEUE
2. DEQUEUE
3. EMPTY CHECK
4. SIZE OF THE QUEUE
5. DISPLAY
6. EXIT
Enter your choice:3
Queue is not empty

***MAIN MENU***
1. ENQUEUE
2. DEQUEUE
3. EMPTY CHECK
4. SIZE OF THE QUEUE
5. DISPLAY
6. EXIT
Enter your choice:6

Circular Queue
In [8]:
class MyCircularQueue():
def __init__(self,k):
self.k = k
self.queue = [None] * k
self.head = self.tail = -1
def enqueue(self, data):
if ((self.tail + 1) % self.k == self.head):
print("The circular queue is full\n")
elif (self.head == -1):
self.head = 0
self.tail = 0
self.queue[self.tail] = data
else:
self.tail = (self.tail + 1) % self.k
self.queue[self.tail] = data
def dequeue(self):
if (self.head == -1):
print("The circular queue is empty\n")
elif (self.head == self.tail):
temp = self.queue[self.head]
self.head = -1
self.tail = -1
return temp
else:
temp = self.queue[self.head]
self.head = (self.head + 1) % self.k
return temp
def printCQueue(self):
if(self.head == -1):
print("No element in the circular queue")
elif (self.tail >= self.head):
for i in range(self.head, self.tail + 1):
print(self.queue[i], end=" ")
print()
else:
for i in range(self.head, self.k):
print(self.queue[i], end=" ")
for i in range(0, self.tail + 1):
print(self.queue[i], end=" ")
print()
obj = MyCircularQueue(5)
obj.enqueue(1)
obj.enqueue(2)
obj.enqueue(3)
obj.enqueue(4)
obj.enqueue(5)
print("Initial queue")
obj.printCQueue()
obj.dequeue()
print("After removing an element from the queue")
obj.printCQueue()

Initial queue
1 2 3 4 5
After removing an element from the queue
2 3 4 5

Priority Queue
In [4]:
from queue import PriorityQueue

q = PriorityQueue()

# insert into queue


q.put((2, 'g'))
q.put((3, 'e'))
q.put((4, 'k'))
q.put((5, 's'))
q.put((1, 'e'))

# remove and return


# lowest priority item
print(q.get())
print(q.get())

# check queue size


print('Items in queue :', q.qsize())

# check if queue is empty


print('Is queue empty :', q.empty())

# check if queue is full


print('Is queue full :', q.full())

(1, 'e')
(2, 'g')
Items in queue : 3
Is queue empty : False
Is queue full : False

Single Linked List


In [2]:
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def insert_at_beginning(self,data):
new_node=Node(data)
if self.head==None:
self.head=new_node
else:
new_node.next=self.head
self.head=new_node
def insert_at_index(self, data, index):
new_node = Node(data)
current_node = self.head
position = 0
if position == index:
self.insert_at_beginning(data)
else:
while(current_node != None and position+1 != index):
position = position+1
current_node = current_node.next
if current_node != None:
new_node.next = current_node.next
current_node.next = new_node
else:
print("Index not present")
def insert_at_end(self,data):
new_node=Node(data)
if self.head==None:
self.head=new_node
current_node=self.head
while(current_node.next):
current_node=current_node.next
current_node.next=new_node
def delete_at_beginning(self):
if(self.head==None):
return
self.head=self.head.next
def delete_at_index(self,index):
if self.head == None:
return
current_node = self.head
position = 0
if position == index:
self.delete_at_beginning()
else:
while(current_node != None and position+1 != index):
position = position+1
current_node = current_node.next
if current_node != None:
current_node.next = current_node.next.next
else:
print("Index not present")
def delete_at_end(self):
if self.head is None:
return
current_node=self.head
while(current_node.next.next):
current_node=current_node.next
current_node.next=None
def display(self):
current_node = self.head
while(current_node):
print(current_node.data,end=" ")
current_node = current_node.next
lnk=LinkedList()
while True:
print("\n***MAIN MENU***\n1.INSERT AT BEGINNING\n2.INSERT AT ANY INDEX\n3.INSERT AT END\n4.DELETE AT BEGINNING\n5.DELETE AT ANY INDEX\n6.DELETE AT END\n7.DISPLAY\n8.EXIT")
choice=int(input("Enter your choice:"))
if(choice==1):
data=input("Enter the value:")
lnk.insert_at_beginning(data)
elif(choice==2):
data=input("Enter the value:")
index=int(input("Enter the index:"))
lnk.insert_at_index(data,index)
elif(choice==3):
data=input("Enter the value:")
lnk.insert_at_end(data)
elif(choice==4):
lnk.delete_at_beginning()
elif(choice==5):
index=int(input("Enter the index:"))
lnk.delete_at_index(index)
elif(choice==6):
lnk.delete_at_end()
elif(choice==7):
lnk.display()
elif(choice==8):
break
else:
print("Enter a valid choice")

***MAIN MENU***
1.INSERT AT BEGINNING
2.INSERT AT ANY INDEX
3.INSERT AT END
4.DELETE AT BEGINNING
5.DELETE AT ANY INDEX
6.DELETE AT END
7.DISPLAY
8.EXIT
Enter your choice:1
Enter the value:10

***MAIN MENU***
1.INSERT AT BEGINNING
2.INSERT AT ANY INDEX
3.INSERT AT END
4.DELETE AT BEGINNING
5.DELETE AT ANY INDEX
6.DELETE AT END
7.DISPLAY
8.EXIT
Enter your choice:1
Enter the value:20

***MAIN MENU***
1.INSERT AT BEGINNING
2.INSERT AT ANY INDEX
3.INSERT AT END
4.DELETE AT BEGINNING
5.DELETE AT ANY INDEX
6.DELETE AT END
7.DISPLAY
8.EXIT
Enter your choice:2
Enter the value:15
Enter the index:1

***MAIN MENU***
1.INSERT AT BEGINNING
2.INSERT AT ANY INDEX
3.INSERT AT END
4.DELETE AT BEGINNING
5.DELETE AT ANY INDEX
6.DELETE AT END
7.DISPLAY
8.EXIT
Enter your choice:3
Enter the value:30

***MAIN MENU***
1.INSERT AT BEGINNING
2.INSERT AT ANY INDEX
3.INSERT AT END
4.DELETE AT BEGINNING
5.DELETE AT ANY INDEX
6.DELETE AT END
7.DISPLAY
8.EXIT
Enter your choice:7
20 15 10 30
***MAIN MENU***
1.INSERT AT BEGINNING
2.INSERT AT ANY INDEX
3.INSERT AT END
4.DELETE AT BEGINNING
5.DELETE AT ANY INDEX
6.DELETE AT END
7.DISPLAY
8.EXIT
Enter your choice:4

***MAIN MENU***
1.INSERT AT BEGINNING
2.INSERT AT ANY INDEX
3.INSERT AT END
4.DELETE AT BEGINNING
5.DELETE AT ANY INDEX
6.DELETE AT END
7.DISPLAY
8.EXIT
Enter your choice:6

***MAIN MENU***
1.INSERT AT BEGINNING
2.INSERT AT ANY INDEX
3.INSERT AT END
4.DELETE AT BEGINNING
5.DELETE AT ANY INDEX
6.DELETE AT END
7.DISPLAY
8.EXIT
Enter your choice:5
Enter the index:1

***MAIN MENU***
1.INSERT AT BEGINNING
2.INSERT AT ANY INDEX
3.INSERT AT END
4.DELETE AT BEGINNING
5.DELETE AT ANY INDEX
6.DELETE AT END
7.DISPLAY
8.EXIT
Enter your choice:7
15
***MAIN MENU***
1.INSERT AT BEGINNING
2.INSERT AT ANY INDEX
3.INSERT AT END
4.DELETE AT BEGINNING
5.DELETE AT ANY INDEX
6.DELETE AT END
7.DISPLAY
8.EXIT
Enter your choice:8

Circular Linked List


In [24]:
class Node:
def __init__(self, data):
self.data = data
self.next = None

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

# Insert a new node at the beginning of the list


def insert_at_beginning(self, data):
new_node = Node(data)
if self.head is None:
new_node.next = new_node
self.head = new_node
else:
temp = self.head
while temp.next != self.head:
temp = temp.next
temp.next = new_node
new_node.next = self.head
self.head = new_node

# Insert a new node at the end of the list


def insert_at_end(self, data):
new_node = Node(data)
if self.head is None:
new_node.next = new_node
self.head = new_node
else:
temp = self.head
while temp.next != self.head:
temp = temp.next
temp.next = new_node
new_node.next = self.head

# Insert a new node at a specific position


def insert_at_position(self, data, position):
if position < 0:
print("Invalid position")
return
new_node = Node(data)
if position == 0:
self.insert_at_beginning(data)
return
temp = self.head
count = 1
while temp is not None and count < position:
temp = temp.next
count += 1
if temp is None:
print("Invalid position")
else:
new_node.next = temp.next
temp.next = new_node

# Delete a node with the given data


def delete_node(self, data):
if self.head is None:
print("List is empty")
return
temp = self.head
prev = None
while temp is not None:
if temp.data == data:
if prev is None: # Deleting head node
if temp.next == self.head: # Single node in the list
self.head = None
else:
last_node = temp
while last_node.next != self.head:
last_node = last_node.next
last_node.next = temp.next
self.head = temp.next
else:
prev.next = temp.next
temp = None # Break the loop after deletion
break
prev = temp
temp = temp.next
if temp is None:
print("Node not found")

# Display the contents of the list


def display(self):
temp = self.head
if temp is None:
print("List is empty")
return
print("List contents:")
while True:
print(temp.data, end=" -> ")
temp = temp.next
if temp == self.head:
break
print("HEAD")

# Example usage
cll = CircularLinkedList()
cll.insert_at_end(10)
cll.insert_at_beginning(5)
cll.insert_at_position(20, 1)
cll.display() # Output: List contents: 5 -> 20 -> 10 -> HEAD

cll.delete_node(20)
cll.display() # Output: List contents: 5 -> 10 -> HEAD

cll.insert_at_end(30)
cll.display() # Output: List contents: 5 -> 10 -> 30 -> HEAD

List contents:
5 -> 20 -> 10 -> HEAD
List contents:
5 -> 10 -> HEAD
List contents:
5 -> 10 -> 30 -> HEAD

Doubly Linked List


In [25]:
import gc
# node creation
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None

class DoublyLinkedList:

def __init__(self):
self.head = None

# insert node at the front


def insert_front(self, data):

# allocate memory for newNode and assign data to newNode


new_node = Node(data)

# make newNode as a head


new_node.next = self.head

# assign null to prev (prev is already none in the constructore)

# previous of head (now head is the second node) is newNode


if self.head is not None:
self.head.prev = new_node

# head points to newNode


self.head = new_node

# insert a node after a specific node


def insert_after(self, prev_node, data):

# check if previous node is null


if prev_node is None:
print("previous node cannot be null")
return

# allocate memory for newNode and assign data to newNode


new_node = Node(data)

# set next of newNode to next of prev node


new_node.next = prev_node.next

# set next of prev node to newNode


prev_node.next = new_node

# set prev of newNode to the previous node


new_node.prev = prev_node

# set prev of newNode's next to newNode


if new_node.next:
new_node.next.prev = new_node

# insert a newNode at the end of the list


def insert_end(self, data):

# allocate memory for newNode and assign data to newNode


new_node = Node(data)

# assign null to next of newNode (already done in constructor)

# if the linked list is empty, make the newNode as head node


if self.head is None:
self.head = new_node
return

# store the head node temporarily (for later use)


temp = self.head

# if the linked list is not empty, traverse to the end of the linked list
while temp.next:
temp = temp.next

# now, the last node of the linked list is temp

# assign next of the last node (temp) to newNode


temp.next = new_node

# assign prev of newNode to temp


new_node.prev = temp

return

# delete a node from the doubly linked list


def deleteNode(self, dele):

# if head or del is null, deletion is not possible


if self.head is None or dele is None:
return

# if del_node is the head node, point the head pointer to the next of del_node
if self.head == dele:
self.head = dele.next

# if del_node is not at the last node, point the prev of node next to del_node to the previous of del_node
if dele.next is not None:
dele.next.prev = dele.prev

# if del_node is not the first node, point the next of the previous node to the next node of del_node
if dele.prev is not None:
dele.prev.next = dele.next

# free the memory of del_node


gc.collect()

# print the doubly linked list


def display_list(self, node):

while node:
print(node.data, end="->")
last = node
node = node.next

# initialize an empty node


d_linked_list = DoublyLinkedList()

d_linked_list.insert_end(5)
d_linked_list.insert_front(1)
d_linked_list.insert_front(6)
d_linked_list.insert_end(9)

# insert 11 after head


d_linked_list.insert_after(d_linked_list.head, 11)

# insert 15 after the seond node


d_linked_list.insert_after(d_linked_list.head.next, 15)

d_linked_list.display_list(d_linked_list.head)

# delete the last node


d_linked_list.deleteNode(d_linked_list.head.next.next.next.next.next)

print()
d_linked_list.display_list(d_linked_list.head)

6->11->15->1->5->9->
6->11->15->1->5->

Stack using Linked List


In [5]:
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList():
def __init__(self):
self.head=None
def push(self,data):
new_node=Node(data)
if self.head==None:
self.head=new_node
else:
current=self.head
while(current.next):
current=current.next
current.next=new_node
def pop(self):
if self.head==None:
print("List is empty")
else:
current=self.head
while(current.next.next):
current=current.next
current.next=None
def display(self):
current=self.head
while(current):
print(current.data,end=" ")
current=current.next
def isEmpty(self):
if self.head==None:
return True
else:
return False
def top(self):
if self.head==None:
print("Linked List is empty")
else:
current=self.head
while(current.next):
current=current.next
print("Top element: ",current.data)
lnk=LinkedList()
while True:
print("\n***MAIN MENU***\n1.PUSH\n2.POP\n3.DISPLAY\n4.EMPTY CHECK\n5.TOP\n6.EXIT")
choice=int(input("Enter your choice:"))
if(choice==1):
data=input("Enter the value:")
lnk.push(data)
elif(choice==2):
lnk.pop()
elif(choice==3):
lnk.display()
elif(choice==4):
print("Is Empty?: ",lnk.isEmpty())
elif(choice==5):
lnk.top()
elif(choice==6):
break
else:
print("Enter a valid choice")

***MAIN MENU***
1.PUSH
2.POP
3.DISPLAY
4.EMPTY CHECK
5.TOP
6.EXIT
Enter your choice:1
Enter the value:10

***MAIN MENU***
1.PUSH
2.POP
3.DISPLAY
4.EMPTY CHECK
5.TOP
6.EXIT
Enter your choice:1
Enter the value:20

***MAIN MENU***
1.PUSH
2.POP
3.DISPLAY
4.EMPTY CHECK
5.TOP
6.EXIT
Enter your choice:1
Enter the value:30

***MAIN MENU***
1.PUSH
2.POP
3.DISPLAY
4.EMPTY CHECK
5.TOP
6.EXIT
Enter your choice:3
10 20 30
***MAIN MENU***
1.PUSH
2.POP
3.DISPLAY
4.EMPTY CHECK
5.TOP
6.EXIT
Enter your choice:2

***MAIN MENU***
1.PUSH
2.POP
3.DISPLAY
4.EMPTY CHECK
5.TOP
6.EXIT
Enter your choice:3
10 20
***MAIN MENU***
1.PUSH
2.POP
3.DISPLAY
4.EMPTY CHECK
5.TOP
6.EXIT
Enter your choice:4
Is Empty?: False

***MAIN MENU***
1.PUSH
2.POP
3.DISPLAY
4.EMPTY CHECK
5.TOP
6.EXIT
Enter your choice:5
Top element: 20

***MAIN MENU***
1.PUSH
2.POP
3.DISPLAY
4.EMPTY CHECK
5.TOP
6.EXIT
Enter your choice:6

Queue using Linked List


In [6]:
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def enqueue(self,data):
new_node=Node(data)
if self.head==None:
self.head=new_node
else:
current=self.head
while(current.next):
current=current.next
current.next=new_node
def dequeue(self):
if self.head==None:
print("Linked List is empty")
else:
self.head=self.head.next
def isEmpty(self):
if(self.head==None):
return True
else:
return False
def peek(self):
if(self.head==None):
print("Linked List is Empty")
else:
print("Peek element is: ",self.head.data)
def display(self):
current=self.head
while(current):
print(current.data,end=" ")
current=current.next
lnk=LinkedList()
while True:
print("\n***MAIN MENU***\n1.ENQUEUE\n2.DEQUEUE\n3.DISPLAY\n4.EMPTY CHECK\n5.PEEK\n6.EXIT")
choice=int(input("Enter your choice:"))
if(choice==1):
data=input("Enter the value:")
lnk.enqueue(data)
elif(choice==2):
lnk.dequeue()
elif(choice==3):
lnk.display()
elif(choice==4):
print("Is Empty?: ",lnk.isEmpty())
elif(choice==5):
lnk.peek()
elif(choice==6):
break
else:
print("Enter a valid choice")

***MAIN MENU***
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EMPTY CHECK
5.PEEK
6.EXIT
Enter your choice:1
Enter the value:10

***MAIN MENU***
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EMPTY CHECK
5.PEEK
6.EXIT
Enter your choice:1
Enter the value:20

***MAIN MENU***
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EMPTY CHECK
5.PEEK
6.EXIT
Enter your choice:1
Enter the value:30

***MAIN MENU***
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EMPTY CHECK
5.PEEK
6.EXIT
Enter your choice:3
10 20 30
***MAIN MENU***
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EMPTY CHECK
5.PEEK
6.EXIT
Enter your choice:2

***MAIN MENU***
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EMPTY CHECK
5.PEEK
6.EXIT
Enter your choice:3
20 30
***MAIN MENU***
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EMPTY CHECK
5.PEEK
6.EXIT
Enter your choice:4
Is Empty?: False

***MAIN MENU***
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EMPTY CHECK
5.PEEK
6.EXIT
Enter your choice:5
Peek element is: 20

***MAIN MENU***
1.ENQUEUE
2.DEQUEUE
3.DISPLAY
4.EMPTY CHECK
5.PEEK
6.EXIT
Enter your choice:6

Binary Search
In [4]:
def binary_search(array,target,low,high):
while low<=high:
mid=low+(high-low)//2
if array[mid]==target:
return mid
elif array[mid]<target:
low=mid+1
else:
high=mid-1
return -1
array=[2,3,4,5,6,7,8,9]
target=int(input("Enter your search element:"))
result=binary_search(array,target,0,len(array)-1)
if result!=-1:
print("Found at:",result)
else:
print("Not Found")

Enter your search element:9


Found at: 7

Linear Search
In [26]:
# Linear Search in Python
def linearSearch(array, n, x):
# Going through array sequencially
for i in range(0, n):
if (array[i] == x):
return i
return -1
array = [2, 4, 0, 1, 9]
x = 1
n = len(array)
result = linearSearch(array, n, x)
if(result == -1):
print("Element not found")
else:
print("Element found at index: ", result)

Element found at index: 3

Bubble Sort
In [27]:
def bubbleSort(array):
# loop to access each array element
for i in range(len(array)):
# loop to compare array elements
for j in range(0, len(array) - i - 1):
# compare two adjacent elements
# change > to < to sort in descending order
if array[j] > array[j + 1]:
# swapping elements if elements
# are not in the intended order
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp
data = [-2, 45, 0, 11, -9]
bubbleSort(data)
print('Sorted Array in Ascending Order:')
print(data)

Sorted Array in Ascending Order:


[-9, -2, 0, 11, 45]

Selection Sort
In [28]:
def selectionSort(array, size):
for step in range(size):
min_idx = step
for i in range(step + 1, size):
# to sort in descending order, change > to < in this line
# select the minimum element in each loop
if array[i] < array[min_idx]:
min_idx = i
# put min at the correct position
(array[step], array[min_idx]) = (array[min_idx], array[step])
data = [-2, 45, 0, 11, -9]
size = len(data)
selectionSort(data, size)
print('Sorted Array in Ascending Order:')
print(data)

Sorted Array in Ascending Order:


[-9, -2, 0, 11, 45]

Insertion Sort
In [29]:
def insertionSort(array):
for step in range(1, len(array)):
key = array[step]
j = step - 1
# Compare key with each element on the left of it until an element smaller than it is found
# For descending order, change key<array[j] to key>array[j].
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j = j - 1
# Place key at after the element just smaller than it.
array[j + 1] = key
data = [9, 5, 1, 4, 3]
insertionSort(data)
print('Sorted Array in Ascending Order:')
print(data)

Sorted Array in Ascending Order:


[1, 3, 4, 5, 9]

Quick Sort
In [33]:
# function to find the partition position
def partition(array, low, high):
# choose the rightmost element as pivot
pivot = array[high]
# pointer for greater element
i = low - 1
# traverse through all elements
# compare each element with pivot
for j in range(low, high):
if array[j] <= pivot:
# if element smaller than pivot is found
# swap it with the greater element pointed by i
i = i + 1
# swapping element at i with element at j
(array[i], array[j]) = (array[j], array[i])
# swap the pivot element with the greater element specified by i
(array[i + 1], array[high]) = (array[high], array[i + 1])
# return the position from where partition is done
return i + 1
# function to perform quicksort
def quickSort(array, low, high):
if low < high:
# find pivot element such that
# element smaller than pivot are on the left
# element greater than pivot are on the right
pi = partition(array, low, high)
# recursive call on the left of pivot
quickSort(array, low, pi - 1)
# recursive call on the right of pivot
quickSort(array, pi + 1, high)
data = [8, 7, 2, 1, 0, 9, 6]
print("Unsorted Array")
print(data)
size = len(data)
quickSort(data, 0, size - 1)
print('Sorted Array in Ascending Order:')
print(data)

Unsorted Array
[8, 7, 2, 1, 0, 9, 6]
Sorted Array in Ascending Order:
[0, 1, 2, 6, 7, 8, 9]

Merge Sort
In [34]:
def mergeSort(array):
if len(array) > 1:
# r is the point where the array is divided into two subarrays
r = len(array)//2
L = array[:r]
M = array[r:]
# Sort the two halves
mergeSort(L)
mergeSort(M)
i = j = k = 0
# Until we reach either end of either L or M, pick larger among
# elements L and M and place them in the correct position at A[p..r]
while i < len(L) and j < len(M):
if L[i] < M[j]:
array[k] = L[i]
i += 1
else:
array[k] = M[j]
j += 1
k += 1
# When we run out of elements in either L or M,
# pick up the remaining elements and put in A[p..r]
while i < len(L):
array[k] = L[i]
i += 1
k += 1
while j < len(M):
array[k] = M[j]
j += 1
k += 1
# Print the array
def printList(array):
for i in range(len(array)):
print(array[i], end=" ")
print()
# Driver program
if __name__ == '__main__':
array = [6, 5, 12, 10, 9, 1]
mergeSort(array)
print("Sorted array is: ")
printList(array)

Sorted array is:


1 5 6 9 10 12

Heap Sort
In [36]:
def heapify(arr, n, i):
# Find largest among root and children
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 root is not largest, swap with largest and continue heapifying
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
# Build max heap
for i in range(n//2, -1, -1):
heapify(arr, n, i)
for i in range(n-1, 0, -1):
# Swap
arr[i], arr[0] = arr[0], arr[i]
# Heapify root element
heapify(arr, i, 0)
arr = [1, 12, 9, 5, 6, 10]
heapSort(arr)
n = len(arr)
print("Sorted array is")
for i in range(n):
print("%d " % arr[i], end='')

Sorted array is
1 5 6 9 10 12

You might also like