How To Use Popular Data Structures and Algorithms in Python ?
How To Use Popular Data Structures and Algorithms in Python ?
List
numbers = []
numbers.append(1)
numbers.append(2)
numbers.append(3)
# Output
'''
1
2
3
'''
numbers = [1, 2, 3]
length = len(numbers)
for i in range(length):
print(numbers[i])
# Output
'''
1
2
3
'''
Strings
string = 'Hello world'
Sorting a list
a = [2, 4, 1, 9, 8]
a.sort()
print(a)
# Output: [1, 2, 4, 8, 9]
Sorting a string
s = 'shivam'
sorted_s = ''.join(sorted(s))
print(sorted_s)
Dictionary
d = {'1': 'Dhoni', '2': 'Sachin', '3': 'Dravid'}
# Output
'''
1 Dhoni
2 Sachin
3 Dravid
'''
d = {}
# Output
'''
1 1
2 4
3 9
4 16
5 25
'''
Converting a char into integer and vice-versa
import heapq
L = []
heapq.heapify(L) # Min heap
heapq.heappush(L, 3) # Pushing 3 into heap
heapq.heappush(L, 2) # Pushing 2 into heap
print(heapq.heappop(L)) # Popping the minimum element
How to use max heap in Python - Multiply each number with -1 while pushing the element in
the heap.
q = deque([])
q.append(1)
q.append(2)
q.append(3)
print(q.popleft()) # 1 will be popped out and printed
print(q.popleft()) #2 will be popped out and printed
Using stack in Python
stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print(stack.pop()) # Will remove 3 from stack and print
it
print(stack.pop()) # Will remove 2 from stack and print
it
stack = deque([])
stack.append(1)
stack.append(2)
stack.append(3)
# Output:
'''
00000
00000
00000
00000
00000
'''
s = set()
s.add(1)
s.add(4)
s.add(3)
s.add(1)
print(s) # Prints {1, 3, 4}
Ordered dictionary in Python
d = OrderedDict()
d[1] = 2
d[2] = 3
d[3] = 4
# output
# 1 2
# 2 3
# 3 4
graph = defaultdict(list)
graph[1].append(2) # 1 -> 2
graph[2].append(3) # 1 -> 2 -> 3
graph[4].append(1) # 4 -> 1 -> 2 -> 3
visited = set()
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def traverse(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
ll = LinkedList()
ll.insert_at_end(1)
ll.insert_at_end(2)
ll.insert_at_end(3)
ll.traverse() # 1 -> 2 -> 3
Binary Tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.left = Node(5)
def inorder(root):
if not root:
return
print(root.data)
inorder(root.left)
inorder(root.right)
inorder(root)
There is also a binary tree module in Python but it doesn’t come pre-installed in the standard
modules. You can read about it here.