Skip to content

Python Reference

Abstract

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

This reference is purposely limited to these problems.

Generated with love by AI.

# Lists
nums = [1, 2, 3]  # [1, 2, 3]
nums[0]  # 1
nums[-1]  # 3
nums[1:3]  # [2, 3]
nums[::-1]  # [3, 2, 1]

# Strings
s = "abc"
s[0]  # 'a'
s[1:]  # 'bc'
s[::-1]  # 'cba'

# Dict
d = {"a": 1}
d["a"]  # 1
d.get("b", 0)  # 0

# Set
seen = set()
seen.add(3)
3 in seen  # True

# Looping
for i in range(3):
    pass
# i goes 0, 1, 2

for i in range(1, 4):
    pass
# i goes 1, 2, 3

for i in range(5, 0, -1):
    pass
# i goes 5, 4, 3, 2, 1

# enumerate
for i, x in enumerate(["a", "b"]):
    pass
# (i, x) = (0, 'a'), (1, 'b')

# zip
list(zip([1, 2], [3, 4]))  # [(1, 3), (2, 4)]

# Conditionals
x = 5
if x > 0:
    y = "pos"
else:
    y = "non-pos"
y  # 'pos'

# Tuple swap
a, b = 1, 2
a, b = b, a
(a, b)  # (2, 1)

# Integer division and modulo
7 // 3  # 2
7 % 3  # 1

# Reverse loop often used for carries / reverse scanning
list(range(3, -1, -1))  # [3, 2, 1, 0]

# len / sum
len([1, 2, 3])  # 3
sum([1, 2, 3])  # 6
min(4, 2)  # 2
max(4, 2)  # 4
sorted([3, 1, 2])  # [1, 2, 3]

# any / all
any([False, True, False])  # True
all([True, True, False])  # False

# list methods
arr = [3, 1, 2]
arr.append(4)
arr  # [3, 1, 2, 4]
arr.pop()
# 4
arr  # [3, 1, 2]
arr.reverse()
arr  # [2, 1, 3]

# string methods
"a".isalnum()  # True
"!".isalnum()  # False
"A".lower()  # 'a'
"7".isdigit()  # True
"abc".find("bc")  # 1

# ord
ord("0")  # 48
ord("7") - ord("0")  # 7

# bit operations
0b101 # 5
bin(5) # "0b101"
format(5, "b") # "101"
format(5, "08b") # "00000101"
5 & 1  # 1
4 & 1  # 0
bin(0b101 | 0b10)  # 0b111
bin(0b101 ^ 0b111)  # 0b10
bin(0b101 << 1)  # 0b1010
bin(0b100 << 1)  # 0b1000
bin(0b101 >> 1)  # 0b10
bin(0b100 >> 1)  # 0b10

# Python 3.8+ int bit count
bin(11) # "0b1011"
(11).bit_count()  # 3

# randrange
from random import randrange

randrange(10)      # 0 to 9
randrange(1, 10)   # 1 to 9
randrange(0, 20, 2)  # even number from 0 to 18

# shuffle
from random import shuffle

items = [1, 2, 3, 4, 5]
shuffle(items)
items # list in random order

# deque
from collections import deque

q = deque([1, 2, 3])
q.appendleft(0)
q # deque([0, 1, 2, 3])
q.popleft()  # 0
list(q) # [1, 2, 3]

# Slice assignment mutates same list object
a = [1, 2, 3, 4]
a[:] = [5, 6]
a  # [5, 6]
a = [1, 2, 3, 4]
a[1:3] = [5, 6]
a  # [1, 5, 6, 4]

# Useful for LeetCode in-place APIs
nums = [1, 2, 3, 4]
nums[:] = nums[::-1]
nums  # [4, 3, 2, 1]

# Counter intersection
from collections import Counter

Counter([1,2,2,2,3,4]) # Counter({2: 3, 1: 1, 3: 1, 4: 1})
Counter([2,2]) # Counter({2: 2})
Counter([1,2,2,2,3,4]) & Counter([2,2]) # Counter({2: 2})
list((Counter([1,2,2,2,3,4]) & Counter([2,2])).elements()) # [2, 2]

# Reverse loop for carry / right-to-left scans
list(range(2, -1, -1))  # [2, 1, 0]

# Common leetcode helpers

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right