Skip to content

Coding

Conversions

int(my_string)    # Convert String to Int
str(my_int)       # Convert to String
ord(my_string)    # Convert to Unicode
chr(my_int)       # Convert Int to Character
bin(my_int)       # Convert Int to Binary String

Math

random.choice(seq)   # Return a rand ele from non empty seq
math.max(seq)        # Max of seq
math.min(seq)        # Min of seq
math.sum(seq)        # Sum of seq
math.ceil(val)       # Ceiling of a value
math.floor(val)      # Floor of a value
val // 2             # Divide and get floor
math.sqrt(num)       # Square Root
math.inf             # Infinity

Strings

my_str.isalpha()  # Letters
my_str.isalnum()  # Letters + Num
my_str.numeric()  # Numbers
my_str.lower()    # Lowercase
my_str.upper()    # Uppercase
my_str.space()    # Space
my_str.lower()    # To lowercase
my_str.upper()    # To Upper
my_str[::-1]      # Reverse
my_str.replace(old_val, new_val) # Replace
my_str.stripe()   # Remove whitespace
my_str.split('.') # Split string into list

Loops

for x in range(len(my_list)):                        # Basic Loop
for idx, value in enumerate(my_list):                # Enumerate
for idx, value in reversed(list(enumerate(my_list))) # Reversed Enumerate
for x in my_set                                      # Loop through set

Lists

my_list = []
"".join(my_list)            # Convert list to string
"".join(map(str, my_list))) # Array of ints to string
my_list.pop()               # Remove from right end O(1)
my_list.pop(item)           # Remove item O(n)
my_list.insert(idx, item)   # Add item after idx O(n)
del my_list[idx]            # Delete item at idx
my_list.sort()              # Sorts list in place
sorted_list(my_list)        # No side effects
my_list1 + my_list2         # Join lists
my_list1.extend(my_list2)   # Append all items from the iterable

#List traversal
range(start, stop, hop)
range(n) # [0,1,...,n-1] range(1,n) # [1,...,n-1]
range(1,n,2) # [1,3,5,...,n-1] if n is even, or [1,3,5,...,n-2] if n is odd
range(n,-1,-1) # [n,n-1,n-2,...,0]
range(len(arr)) # Provides indices of an array arr
range(len(arr)-1,-1,-1) # Provides indices of arr backwards

# List slicing
arr[w:s] # Wait w elements, start copy (:), stop before reaching index s
arr = [1,2,3,4]
arr[1:] = [2,3,4]
arr[:2] = [1,2]

#List manipulation
arr = [1,2,3]
[str(x) for x in arr] # Output: ['1','2','3']
map(lambda x: str(x), arr) # Output: ['1','2','3']
[str(x) for x in arr if x%2] # Output: ['1','3']

Tuples

dir = [(1,0),(-1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,-1),(-1,1)]
for d in dir:
  x, y = d      # Destructure Tuple Values
# Named Tuple
from collections import namedtuple
Point = namedtuple("Point", "x y")
Point = namedtuple("Point", "x, y")
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)
> p.x # 11
> p.y # 22
x, y = p # Unpacking

Stack

my_stack = deque() 
my_stack.append(item) # Push O(1)
my_stack.pop()        # Pop O(1)
my_stack[-1]          # Peek O(1)
len(my_stack)         # Size O(1)

Queue

from collections import deque
my_queue = deque()
my_queue.append(item) # Push O(1)
my_queue.popleft()    # Pop  O(1)
my_queue.remove(item) # Remove O(n)
len(my_queue)         # Size O(1)

Set

my_set = set()
my_set.add(ele)        # Add
my_set.remove(ele)     # Remove
my_set.discard(ele)    # Remove if present
len(my_set)            # Length
x in my_set            # Test x is in my_set
x not in my_set        # Test x is not in my_set
my_set.union(x)        # All Elements in both sets
my_set.intersection(x) # Common Elements in both sets
my_set.difference(x)   # Elements only in my_set
my_set.issubset(x)     # Checks if my_set is a subset of x

Heap

# Min Heap for Max multiply by -1
import heapq
heap = []
heapq.heapify(list)                 # Turns list into heap O(n)
heapq.heappush(heap, [2, 'a', 'a']) # Add to heap O(log n)
heapq.heappop(heap)                 # Pop smallest element O(log n)
heap[0]                             # Peek smallest 
heapq.heappushpop(heap, ele)        # Pushes new ele to heap then pops the smallest ele
heapq.nlargest(k, heap)             # Return the k largest ele
heapq.nsmallest(k, heap)            # Return the k smallest ele

Dictionary

my_dict = dict()
my_dict = {}
my_dict[key] = value # Set Item
my_dict.update(key)  # Set Item
my_dict[key]         # Get Item - Error if not present
my_dict.get(key)     # Get key or return None if not present
del my_dict[key]     # Remove
my_dict.pop(key)     # Removes and returns value
key in my_dict       # Check if present
key not in my_dict   # Check not present
len(my_dict)         # Size
for key, val in my_dict.items(): # Loop through all keys and values
  print(key, val)
for key in my_dict.keys() # All Keys
  print(key)
for val in my_dict.values() # All Values
  print(val) 

Ordered Dict

from collections import OrderedDict
my_dict = collections.OrderedDict() #Init
my_dict.popitem(last=True)          # LIFO if True, FIFO if False
my_dict.move_to_end(key, last=True) # Move to end, follow above LIFO/FIFO 
my_dict[key] = value                # Add

2D Array

grid = [[3,0,0],[5,2,0],[1,1,0]]
# grid[y][x]
grid[0][0] # 3 
grid[1][1] # 2
grid[1][0] # 5

Default Dict

from collections import defaultdict

## List
> list_dict = defaultdict(list)
> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
> for k, v in s:
      list_dict[k].append(v)
> sorted(list_dict.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

## Int
> int_dict = defaultdict(int)
> s = 'mississippi'
> int_dict = defaultdict(int)
> for k in s:
      int_dict[k] += 1
> sorted(d.items())
[('i', 4), ('m', 1), ('p', 2), ('s', 4)]

## Set
> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
> d = defaultdict(set)
> for k, v in s:
      d[k].add(v)

> sorted(d.items())
[('blue', {2, 4}), ('red', {1, 3})]

Counter

from collections import Counter
my_counter = Counter("Leetcode 4 life!")
sorted(my_counter.elements())
[' ', ' ', '!', '4', 'L', 'c', 'd', 'e', 'e', 'e', 'e', 'f', 'i', 'l', 'o', 't']
Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
sum(c.values())                 # total of all counts
c.clear()                       # reset all counts
list(c)                         # list unique elements
set(c)                          # convert to a set
dict(c)                         # convert to a regular dictionary
c.items()                       # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1]       # n least common elements
+c                              # remove zero and negative counts

Binary Tree

def solution(self, root):
    def solve(root):
        if not root:
            # do something
        solve(root.left)
        solve(root.right)
        return # something
    solve(root)
    return # something

Binary Search T: O(log N) S: O(1)

def binary_search(array) -> int:
  def condition(value) -> bool:
    pass (1)

  left, right = min(search_space), max(search_space) #could be [0, n], [1, n] etc. Depends on prob
  while left < right:
    mid = left + (right - left) // 2
    if condition(mid):
      right = mid
    else:
      left = mid + 1
  return left

DFS

TODO

BFS

TODO