Skip to content

Python Reference

Abstract

Minimal Python reference to solve the 45 problems of LeetCode Top Medium, written after solving them.

This reference is purposely limited to these problems.

# Default dict
from collections import defaultdict

groups = defaultdict(list)

groups # defaultdict(<class 'list'>, {})
groups["foo"] # [] - This would a KeyError with standard dictionary {}
groups # defaultdict(<class 'list'>, {'foo': []})
groups["foo"].append(1)
groups # defaultdict(<class 'list'>, {'foo': [1]})
groups["bar"].append(1)
groups # defaultdict(<class 'list'>, {'foo': [1], 'bar': [1]})



# Infinities as floats
float("-inf") # -inf
float("inf")  # inf
type(float("inf")) # <class 'float'>
float("-inf") < 1 < float("inf") # True



# Heap
import heapq

heap = []

# heappush adds items while keeping heap[0] as the smallest item.
heapq.heappush(heap, 5)
heapq.heappush(heap, 1)
heapq.heappush(heap, 3)

heap       # [1, 5, 3]
heap[0]    # 1

# heapreplace removes and returns the smallest item, then pushes the new item.
removed = heapq.heapreplace(heap, 4)

removed    # 1
heap       # [3, 5, 4]

# nlargest returns the N largest values from any iterable.
heapq.nlargest(2, heap)  # [5, 4]



# Counter - Most common elements
from collections import Counter

items = ["apple", "banana", "apple", "orange", "banana", "apple"]

counts = Counter(items)

# most_common() returns a list of (item, count) pairs,
# sorted from most frequent to least frequent.
counts.most_common() # [('apple', 3), ('banana', 2), ('orange', 1)]

# You can pass a number to get only the top N most common items.
counts.most_common(2) # [('apple', 3), ('banana', 2)]



# Combinatorics
import math

# math.comb(n, k) returns the number of ways to choose k items from n items.
# Order does not matter.
# Example: choose 2 fruits from 4 fruits.

fruits = ["apple", "banana", "cherry", "date"]
math.comb(len(fruits), 2) # 6



# Combinations of elements in an iterable
from itertools import combinations

# Compute all unique (Order does not matter) pairs from the list
list(combinations(["a", "b", "c"], 2)) # [('a', 'b'), ('a', 'c'), ('b', 'c')]



# Find position where to insert value in a sorted list
import bisect

nums = [1, 3, 3, 5, 7]

# bisect_left returns the index where a value should be inserted
# to keep the list sorted.
# If the value already exists, it returns the position BEFORE the first match.

i = bisect.bisect_left(nums, 3)
i # 1
nums.insert(i, 3)
nums # [1, 3, 3, 3, 5, 7]

# For a value not in the list, it returns the sorted insertion position.
bisect.bisect_left(nums, 3.5) # 4
bisect.bisect_left(nums, -1)  # 0
bisect.bisect_left(nums, 8)   # 6



# bit_length() returns the number of bits needed to represent
# a non-negative integer in binary, excluding the "0b" prefix.
for n in [0, 1, 2, 3, 4, 7, 8, 255, 256]:
    print(n, bin(n), n.bit_length())
# 0 0b0 0
# 1 0b1 1
# 2 0b10 2
# 3 0b11 2
# 4 0b100 3
# 7 0b111 3
# 8 0b1000 4
# 255 0b11111111 8
# 256 0b100000000 9