PYTHON STACK & HEAP
~ Stack
tack a, hey si Cae
In Python, a stack isa collection of elements with two main principal operations: push, which adds an element to the collection, and pop, which
temoves the most recently added element, The last element added isthe frst one to be removed, following the Last ln, First Out (LIFO)
principle. Stacks are often used for managing function cals, racking execution history, and solving problems that require a lastin, fist-out
approach.
Implementation of a Stack:
You can implement a stack in Python using lists or collections provided by the coLlections module. Let's explore both methods:
Using Lists:
stock = (1
# Pushing elenerts onto the stack
stock. sppen6(0)
stoce-sppen6(2)
stsce-sppen6(3)
pop_elenent = stack.20p()
et ea ear pcm lait neon Tetgcmpracetnesas asa rt tack a, hey si Cae
Using collections deque
stock = eegu0()
stack. 2ppend(t)
stock. sppen6(2)
stace-sppend(2)
lent = stack. pont)
‘Common Stack Operations:
1, Push (append forlists, append for deque): Adds an element tothe top ofthe stack
stack.sppend(4) or
k.appendleft(4) for deque
2, Pop (pop for lists, pop for deque): Removes and returns the element from the top ofthe stack.
popped elenent = stack.pop() # or popped element
stack-popleft() for deque
3. Peek (Accessing the Top Element):
top_elenent =
k{-2]# for Lists
et ea ear pcm lait neon Tetgcmpracetnesas asa rt tack a, hey si Cae
top_elenent = stack{-1) # for deque
4, Check ifthe Stack is Empty:
s_enpty = not boot(stack) # Retumns True if the stack is enoty
Use Cases for Stacks:
1. Function Call Stack: When a function is called, its local variables and the address to return after the function call are pushed onto the
stack.
2, Expression Evaluation: Stacks can be used to evaluate expressions by converting them to postfix or prefix notation and then using the
‘stack to perform the computation.
3. Undo Mechanism: Stacks are commonly used to implement undo mechanisms in applications.
4, Backtracking Algorithms: Stacks are used in backtracking algorithms to keep track of the path and revert when necessary.
5. Parsing and Syntax Checking: Stacks are used in parsing and syntax checking to keep track of open and close brackets, tags et
Python's list or colections.deque can be used to implement a stack depending on the specific requirements of the application. The choice
between them often depends on the need for additional operations lke O(1) appends and pops on both ends (deque) or simplicity and clarity
(aise)
» Heap
In Python, a heap isa epecialized tree-based data structure that satisfies the heap property. Aheap Is commonly used to implement priority
{queues, where the element withthe highest (or lowest) priority is always atthe root. There are two main types of heaps: min-eap and max:
heap.
et ea ear pcm lait neon Tetgcmpracetne aMin-Heap:
tack a, hey si Cae
Ina min-heap, the value of each node is less than or equal to the values of its children. Therefore, the smallest element is always atthe root
Max-Heap
In amaxcheap, the value of each nade is greater than or equal tothe values of its children, Therefore, the largest element is always atthe root
Heap Operations:
1. Insertion (Push): Adds a new element to the heap while maintaining the heap property.
2, Deletion (Pop): Removes the root element (min or max, depending on the heap type) from the heap while maintaining the heap property.
3. Heapify: Reorders the elements in the heap to satisfy the heap property. This is often used after insertion or deletion
4, Peek: Returns the value of the root element without removing it.
Python Heap Implementation’
In Python, the neapa module provides a simple heap implementation based on alist. It supports both min-heaps and max-heaps.
Neop = (3, 2s 4s 4, 5, 9, 2, 6, 5, 3, 5)
heoracheopify (neo)
heobg.hesppusn(heap, 0)
1 Popping the snaliest elevent (rest) fron the heap
rinelenent = heapa.esppon(heap)
et ea ear pcm lait neon Tetgcmpracetnesas asa rt tack a, hey si Cae
minelenent.peek = heap(o] + Alternatively, sin_elenent_peee = heaps-hesppo9(Fe3p)
cresting a maxcheap (oy negating elenents)
reapeap = [x for x in hen]
heora-tespiéy(esx_he3p)
eoeg-heapbust(nasMeap, -7)
4 Popping the largess element (rest) fron the naxches9
rax_eliment = -eaps.neappan(aax_neap)
rax_elenent,peok = tax nea[@] Alter
vely, max elenent_peek = -heapg.neappop(nax_ heap)
Use Cases for Heaps:
1. Priority Queues: Heaps are commonly used to implement priority queues, where elements are processed based on ther priority.
2. Graph Algorithms: Heaps are used in various graph algorithms, such as Dikstras algorithm and Prims algorithm, to efficiently extract the
minimum (or maximum) element
2, Task Scheduling: Heaps are useful for scheduling tasks based on their priority or deadline,
4. Merge K Sorted Lists: Heaps can efficiently merge k sorted lists into a single sorted is.
5. Order Statistics: Heaps can be used to efficiently find the kth smallest or largest element ina collection.
Python's heap module provides a convenient way to work with heaps, and itis based ona list, which allows for easy integration with other
Python data structures.
et ea ear pcm lait neon Tetgcmpracetne ersas asa rt tack a, hey si Cae
Last-In/First-Out (LIFO) or First-In/Last-Out (FILO)
‘There are three implementation
Stack
collections.deque
queue module
v Stack
Stackis a simple data structure and it stores elements like pile of plates. Operation in stack is done on top of stack meaning, we can perform
Ingertion and deletion on top painter of stack
Consider a pile of 10 numbered plates with Tat the bottom and 10 at the top, o remove plate 5, we need to remove 10, 9, 8,7, 6 then Sin that
‘order, to perform deletion, This procedure of deletion or accessing an element is called Last In First Out (LJFO). The things that comes last, will
bbe removed fst.
stack sa linear data structure that stores items in a Last-ln/First-Out (LIFO) o” First-in/Last-Out (FILO) manner. n stack, a new element is
‘added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop.
Basic operations in Stack
Push — Adding element atthe top of the stack
Pop — Removing the top element from stack
IsEmpty — Check if stack is empty or not
et ea ear pcm lait neon Tetgcmpracetne wrsas asa rt tack a, hey si Cae
size()~ Returns the size of the stack
top() / peek()~ Returns a reference tothe topmost element of the stack
[Full ~ Checkif stack is full or not
et ea ear pcm lait neon Tetgcmpracetne mor# Python progran to
# denonstrate stack inplenentation
# using List
fF append() function to push
f elenent in che stack
stack. append('a")
stack. append('b")
stack.append('e")
stack. append((1,2,3,4,5))
stack-append(2)
stack.append(2)
stack.append(3)
prine(tnstial stack")
print(stack)
# popt) function to pop
print("\nelenents popped fron stack:")
prine(stack.pop())
print(staek:p0p())
print(stack.p0p())
print(stack.p0p())
print("\nstack after elenents are popped:')
print(stack)
uncomenting print(
# will couse an Index
# as the stack is now ety
nstial stack
(late tbs e's Cy 2s 3, My S]e Le 2 3)
et ea ear pcm lait neon Tetgcmpracetne
tack a, hey si Caesas asa rt tack a, hey si Cae
nents popped from stack
[haa as)
Stack after elements are popped
Cat, "br e)
y Implementation using collections.deque:
Python stack can be implemented using the deque class from the collections module. Deque is preferred over thelist inthe cases where we
‘need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop
‘operations as compared to list which provides O(n) time complexity.
et ea ear pcm lait neon Tetgcmpracetne wer4 Python progran to
# demonstrate stack inplenentation
4 using collections desue
from collections tnport deaue
stack = ceque()
# append() function te push
# elenent in the stack
stack.append('a")
stack-append('b*)
stack-append(‘c")
stack.append((2,2,3,4,5])
stack. append(2)
stack. append(2)
stack. append(3)
print("Instial stacks")
print (stack)
1 popt) function to pop
f elenent from stack in
# L1Fo order
print("\nElenents popped fron stack:')
print(stack.pop())
print(stack.p0p())
print stack.pop())
print (stack. 99p())
print("\nstack after elenents are popped:')
print(stack)
+ unconmenting print(stack.popt))
4 wit cause an Indexérror
# a8 the stack 45 now empty
et ea ear pcm lait neon Tetgcmpracetne
tack a, hey si Caesas asa rt tack a, hey si Cae
26s (23 4 ST Le 2 3D)
Elenents popped from stack:
3
[he 28 4
Stack after elements are popped
Geque(i'a", "b', "e'I)
¥ queue module
‘Queue module also has a LIFO Queue, which is basically a Stack. Data inserted into Queue using the put function and get( takes data out
{rom the Queue.
‘There are various functions available in this module:
maxsize ~ Number of items allowed in the queue.
empty) ~ Return True ifthe queue is empty False otherwise,
{ull ~ Return True if there are maxsize tems in the queue, Ifthe queue was initialized with maxsize=0 (the default, then full) never returns
Tue,
‘get0 ~ Remove and return an item from the queue, f the queue is empty, wait until an items available,
‘get_nowaitd)— Retum an item if one is immediately available, else raise QueueEmpty
pput(tem) ~ Put an iter into the queue. If the queue is fll, wait unt a free slot is available before adding the item.
put nowaititem) ~ Put an item into the queve without blocking. Ifno free slot is immediately available, raise QueueFull
qsize() ~ Return the number of items inthe queue
et ea ear pcm lait neon Tetgcmpracetne warsas asa rt tack a, hey si Cae
4 Python progran to
# demonstrate stack inplenentation
using queue nodule
fron queue inport Lifequeue
f ioitializing a stack
stack = Lifoqueue(naxsize=3)
# qsize() show the number of elenents
4 in the stack
print(stack.asize())
f purl) function to push
f elenent in the stack
stack. put("2")
stack. put(b')
stack.put("e")
print "Full: *, stack. full0)
print("Stze: ") stack.asize())
gett) function to pop
# slenent fron stack dn
++ LIFO onder
print("\nElenents popped fron the stack")
print(stack-get())
print(stack-get())
print (stack get())
print("\neapty: ", stack.enpty())
e
Full: True
size: 3
Elesents popped fron the stack
et ea ear pcm lait neon Tetgcmpracetne annsas asa rt ne, onesie Cate
Binary Tree
1. Fall Binary Tree A full Binary tree is @ special type of binary tree in which every parent node/internal node has either two or no children,
2. Perfect Binary Tree A perfect binary tree is a type of binary tree in which every intemal node has exactly two child nodes and allthe leaf
Q
08 Oo
Perfect Binary Tree
Full Binary Tree
ot ene ear spc ilies NOAELIZTesgCAceine tarsas asa rt tack a, hey si Cae
» Heap data structure
+ The Heap data structure can be used to efficiently find the kth smallest (or largest) element in an array
‘+ Whenever elements are pushed or popped, heap structure is maintained, The heapl0] element also returns the smallest element each
time. Lets see various Operations on the heap in Python.
Creating a simple heap The heapify(iterable)-This function is used to convert the iterable into @ heap data structure.
+ importing "heapa” to inplenent heap queve
import heapq
5, 759) 4, 3, 12, 4)
# using heapify to convert List into heap
heapg.heapify(2i)
# printing created heap
print ("The created heap is + *,(2ist(1i)))
[hy 3,4, 7 5) 32, 9)
‘ne created heap 5: (1, 3, 4, 7) 5, 42, 9)
» Appending and Popping Items Efficiently
heappush(heap, ele):
et ea ear pcm lait neon Tetgcmpracetne esrsas asa rt tack a, hey si Cae
This function is used to insert the element mentioned in its arguments into a heap. The order is adjusted, so that heap structure is maintained,
heappop(heap):
This function is used to remove and return the smallest element from the heap. The order is adjusted, so that heap structure is maintained
Double-click (or enter) to edit
et ea ear pcm lait neon Tetgcmpracetne wrsas asa rt tack a, hey si Cae
# importing "heapa” to inplenent heap queve
inportneapq
# using neapify to convert List inte heap
heapg.hespify(1i)
# printing created heap
print("The created heap is: ~, end")
print(ise (iy)
1 using Meappush() to push elenents into heap
# pushes 4
heapa.nesppush(4, 4)
# printing modified heap
print("The modified heap after push is : *, ende"*)
prine(ise(ti))
# using neappop() to pop smallest element
print("The popped and snallest elenent is
prine(hespq.neappop(14))
“yen
print("The mosified heap after POP is : ", end
print(list qi)
The crested heap is : (2, 3, 9, 7, 5]
The modifies heap after push 1S (1, 3, 4, 7, 5» 9]
The popped and smallest elenent is :'1
The nodities heap after POP is + [3, 5, 4, 7, 9]
¥ Appending and Popping simultaneously
et ea ear pcm lait neon Tetgcmpracetneheappushpop(heap, ele):-
tack a, hey si Cae
This function combines the functioning of both push and pop operations in one statement, increasing efficiency. Heap order is maintained after
this operation.
heapreplace(heap, ele):-
This function also inserts and pops elements in one statement, but ii ferent from the above function. In ths, the element is fist popped,
then the element is pushed. ie, the value larger than the pushed value can be returned. heapreplace( returns the smallest value originally in the
heap regardless of the pushed element as opposed to heappushpop0)
f importing "heapa" to Anplenent heap queve
import neapq
# initializing List 2
BMI [51 8 4, 3
# using heapify() to convert List into heap
heapq. heapify(it)
hapa. heapify(i2)
et ea ear pcm lait neon Tetgcmpracetne