Skip to content

Instantly share code, notes, and snippets.

@PseudoSky
Last active July 2, 2020 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PseudoSky/50dcbf2ab5eeef0cae517c01c2919600 to your computer and use it in GitHub Desktop.
Save PseudoSky/50dcbf2ab5eeef0cae517c01c2919600 to your computer and use it in GitHub Desktop.
Data structures & Algorithms
Input : Inorder -> 4 2 5 1 3
        Preorder -> 1 2 4 5 3
        Postorder -> 4 5 2 3 1
Output : Yes
Exaplanation : All of the above three traversals are of 
the same tree              1
                         /   \
                        2     3
                      /   \
                     4     5

Input : Inorder -> 4 2 5 1 3
        Preorder -> 1 5 4 2 3
        Postorder -> 4 1 2 3 5
Output : No 
    
''' Deque for graphs '''
import collections

def breadth_first_search(graph, root): 
    visited, queue = set(), collections.deque([root])
    while queue: 
        vertex = queue.popleft()
        yield vertex
        visited.add(vertex)
        queue.extend(n for n in graph[vertex] if n not in visited)
        
if __name__ == '__main__':
    graph = {1: [2, 4, 5], 2: [3, 6, 7], 3: [], 4: [], 5: [], 6: [], 7: []}
    list(breadth_first_search(graph, 1))  # [1, 2, 4, 5, 3, 6, 7]

Quicksort

# This function takes last element as pivot, places 
# the pivot element at its correct position in sorted 
# array, and places all smaller (smaller than pivot) 
# to left of pivot and all greater elements to right 
# of pivot 
def partition(arr,low,high): 
    i = ( low-1 )         # index of smaller element 
    pivot = arr[high]     # pivot 
  
    for j in range(low , high): 
  
        # If current element is smaller than or 
        # equal to pivot 
        if   arr[j] <= pivot: 
          
            # increment index of smaller element 
            i = i+1 
            arr[i],arr[j] = arr[j],arr[i] 
  
    arr[i+1],arr[high] = arr[high],arr[i+1] 
    return ( i+1 ) 
  
# The main function that implements QuickSort 
# arr[] --> Array to be sorted, 
# low  --> Starting index, 
# high  --> Ending index 
  
# Function to do Quick sort 
def quickSort(arr,low,high): 
    if low < high: 
  
        # pi is partitioning index, arr[p] is now 
        # at right place 
        pi = partition(arr,low,high) 
  
        # Separately sort elements before 
        # partition and after partition 
        quickSort(arr, low, pi-1) 
        quickSort(arr, pi+1, high)
''' -------------------- '''
''' Start: Shortest Path '''
''' -------------------- '''
# https://www.geeksforgeeks.org/shortest-path-faster-algorithm/?ref=leftbar-rightbar
# Python3 implementation of SPFA
from collections import deque
# Graph is stored as vector of vector of pairs
# first element of pair store vertex
# second element of pair store weight
graph = [[] for _ in range(100000)]
# Function to add edges in the graph
# connecting a pair of vertex(frm) and weight
# to another vertex(to) in graph
def addEdge(frm, to, weight):
graph[frm].append([to, weight])
# Function to prshortest distance from source
def print_distance(d, V):
print("Vertex","\t","Distance from source")
for i in range(1, V + 1):
print(i,"\t",d[i])
# Function to compute the SPF algorithm
def shortestPathFaster(S, V):
# Create array d to store shortest distance
d = [10**9]*(V + 1)
# Boolean array to check if vertex
# is present in queue or not
inQueue = [False]*(V + 1)
d[S] = 0
q = deque()
q.append(S)
inQueue[S] = True
while (len(q) > 0):
# Take the front vertex from Queue
u = q.popleft()
inQueue[u] = False
# Relaxing all the adjacent edges of
# vertex taken from the Queue
for i in range(len(graph[u])):
v = graph[u][i][0]
weight = graph[u][i][1]
if (d[v] > d[u] + weight):
d[v] = d[u] + weight
# Check if vertex v is in Queue or not
# if not then append it into the Queue
if (inQueue[v] == False):
q.append(v)
inQueue[v] = True
# Print the result
print_distance(d, V)
# Driver code
if __name__ == '__main__':
V = 5
S = 1
# Connect vertex a to b with weight w
# addEdge(a, b, w)
addEdge(1, 2, 1)
addEdge(2, 3, 7)
addEdge(2, 4, -2)
addEdge(1, 3, 8)
addEdge(1, 4, 9)
addEdge(3, 4, 3)
addEdge(2, 5, 3)
addEdge(4, 5, -3)
# Calling shortestPathFaster function
shortestPathFaster(S, V)
''' -------------------- '''
''' END: Shortest Path '''
''' -------------------- '''
''' ------------------------- '''
''' START: Quicksort Bottom N '''
''' ------------------------- '''
# This function returns k'th smallest element
# in arr[l..r] using QuickSort based method.
# ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT
import sys
def kthSmallest(arr, l, r, k):
# If k is smaller than number of
# elements in array
if (k > 0 and k <= r - l + 1):
# Partition the array around last
# element and get position of pivot
# element in sorted array
pos = partition(arr, l, r)
# If position is same as k
if (pos - l == k - 1):
return arr[pos]
if (pos - l > k - 1): # If position is more,
# recur for left subarray
return kthSmallest(arr, l, pos - 1, k)
# Else recur for right subarray
return kthSmallest(arr, pos + 1, r,
k - pos + l - 1)
# If k is more than number of
# elements in array
return sys.maxsize
# Standard partition process of QuickSort().
# It considers the last element as pivot and
# moves all smaller element to left of it
# and greater elements to right
def partition(arr, l, r):
x = arr[r]
i = l
for j in range(l, r):
if (arr[j] <= x):
arr[i], arr[j] = arr[j], arr[i]
i += 1
arr[i], arr[r] = arr[r], arr[i]
return i
# Driver Code
if __name__ == "__main__":
arr = [12, 3, 5, 7, 4, 19, 26]
n = len(arr)
k = 3;
print("K'th smallest element is",
kthSmallest(arr, 0, n - 1, k))
''' ------------------------- '''
''' END: Quicksort Bottom N '''
''' ------------------------- '''
''' Using defaulted dict structures '''
from collections import defaultdict
student_grades = defaultdict(list) # <= values default to lists
for name, grade in grades:
student_grades[name].append(grade)
''' Top N: using heapq '''
# finding 3 highest values in a Dictionary
from heapq import nlargest
# Initial Dictionary
my_dict = {'A': 67, 'B': 23, 'C': 45,
'D': 56, 'E': 12, 'F': 69}
print("Initial Dictionary:")
print(my_dict, "\n")
ThreeHighest = nlargest(3, my_dict, key = my_dict.get)
print("Dictionary with 3 highest values:")
print("Keys: Values")
for val in ThreeHighest:
print(val, ":", my_dict.get(val))
''' Permutations '''
import itertools
friends = ['Monique', 'Ashish', 'Devon', 'Bernie']
list(itertools.permutations(friends, r=2))
'''
[('Monique', 'Ashish'), ('Monique', 'Devon'), ('Monique', 'Bernie'),
('Ashish', 'Monique'), ('Ashish', 'Devon'), ('Ashish', 'Bernie'),
('Devon', 'Monique'), ('Devon', 'Ashish'), ('Devon', 'Bernie'),
('Bernie', 'Monique'), ('Bernie', 'Ashish'), ('Bernie', 'Devon')]
'''
'''
Iterative dfs:
Given binary tree "t" and target value "s"
Find a path having the sum of its values equal to s
If it exists return true
'''
def dfs_iterative(t, s):
if(t is None): return False
visited = set()
inv = t.value
stack = [t]
while len(stack)>0:
cur = stack[-1]
visited.add(cur)
left = cur.left
right = cur.right
if(cur.left is None and cur.right is None):
inv = sum([l.value for l in stack])
if(inv==s): return True
stack.pop()
elif(cur.left and not cur.left in visited):
stack.append(cur.left)
elif(cur.right and not cur.right in visited):
stack.append(cur.right)
else:
stack.pop()
return False
def dfs_recursive(node, target, partial=0):
if(node is None): return False
p = node.value + partial
if(node.left is None and node.right is None):
return p==target
if(dfs_recursive(node.left, target, p) or dfs_recursive(node.right, target, p)):
return True
return False
# Binary trees are defined with this interface:
# class Tree(object):
# def __init__(self, x):
# self.value = x
# self.left = None
# self.right = None
def isTreeSymmetric_iterative(t):
if(t is None): return True
if(t.left is None and not t.right is None): return False
if(t.right is None and not t.left is None): return False
s = [t.left, t.right]
while len(s):
lhs = s[0]
s.pop(0)
rhs = s[0]
s.pop(0)
if(lhs is None and not rhs is None): return False
if(rhs is None and not lhs is None): return False
if(lhs.value!=rhs.value):
return False
if(lhs.left or rhs.right):
if(rhs.right):
s.append(lhs.left)
s.append(rhs.right)
else:
return False
if(rhs.left or lhs.right):
if(lhs.right):
s.append(lhs.right)
s.append(rhs.left)
else:
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment