Data Structure with Python
Data Structure with Python
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
def getPrecedence(op):
if op=='^':
return 3
elif(op=='*' or op=='/' or op=='%'):
return 2
elif(op=='+' or op=='-'):
return 1
else:
return -1
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()
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)
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()
(1, 'e')
(2, 'g')
Items in queue : 3
Is queue empty : False
Is queue full : False
***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
class CircularLinkedList:
def __init__(self):
self.head = None
# 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
class DoublyLinkedList:
def __init__(self):
self.head = None
# if the linked list is not empty, traverse to the end of the linked list
while temp.next:
temp = temp.next
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
while node:
print(node.data, end="->")
last = node
node = node.next
d_linked_list.insert_end(5)
d_linked_list.insert_front(1)
d_linked_list.insert_front(6)
d_linked_list.insert_end(9)
d_linked_list.display_list(d_linked_list.head)
print()
d_linked_list.display_list(d_linked_list.head)
6->11->15->1->5->9->
6->11->15->1->5->
***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
***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")
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)
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)
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)
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)
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)
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