a-z
ascii_lowercase
ord('a')
ord('b')
chr(97)
chr(98)
"str123".isalnum()
String
"hello".index("hel")
"hello".index("world")
"hello".find("hel")
"hello".find("world")
Bit
(5).bit_length()
(8).bit_length()
(5).bit_count()
(8).bit_count()
x & -x
000010
x & (x + 1)
x & (x - 1)
Iterator
pairwise
for x, y in pairwise("abbcccc"):
print(x, y)
"""
a b
b b
b c
c c
c c
c c
"""
zip
la = ['a1', 'a2', 'a3']
lb = ['b1', 'b2', 'b3']
lc = ['c1', 'c2', 'c3']
for a, b, c in zip(la, lb, lc):
print(a, b, c)
"""
a1 b1 c1
a2 b2 c2
a3 b3 c3
"""
permutations
nums = [3,4,1]
permutations(nums)
"""
(3, 4, 1)
(3, 1, 4)
(4, 3, 1)
(4, 1, 3)
(1, 3, 4)
(1, 4, 3)
"""
Search
bisect
arr = [1, 2, 3, 3, 3, 5, 6]
print(bisect_left(arr, 3))
print(bisect_right(arr, 3))
arr = [1, 2, 3, 5, 6]
print(bisect_left(arr, 4))
print(bisect_right(arr, 4))
Sort
list.sort()
list.sort(reverse=True)
sorted([3, 2])
t = [('a', 5), ('e', 1),('c', 3), ('b', 2)]
t.sort(key=lambda c: c[1])
for i in t:
print(i)
def cmp(a, b):
return a.bit_length() - b.bit_length()
nums.sort(key=cmp_to_key(cmp))
Data Structure
List
a = [1, 2, 3, 4, 5]
a[::-1]
b = [1, 2, 3]
b.extend([4, 5, 6])
b
2d Array
matrix = [[0] * N for _ in range(M)]
Queue
q = deque([1,2,3])
q.append(4)
v = q.popleft()
q.clear()
Dict
graph = defaultdict(list)
edges = [[1, 2], [0, 2], [0, 1], [3, 4]]
for [n1, n2] in edges:
graph[n1].append(n2)
Counter
cnt = Counter()
s = "aaabbcc"
for c in s:
cnt[c] += 1
for k, v in cnt.items():
print(k, v)
s = "aaaabbb"
s.count('a')
nums = [1,1,2,2,3,4,2,3]
cnt = Counter(nums)
cnt.most_common()
Heap
arr = []
heapq.heapify(arr)
heapq.heappush(arr, 7)
heapq.heappop(arr)
class MaxHeap:
def __init__(self):
self.data = []
def top(self):
return -self.data[0]
def push(self, val):
heapq.heappush(self.data, -val)
def pop(self):
return -heapq.heappop(self.data)
Math
a = [1, 2, 3, 4, 5]
list(accumulate(a))
nums = [3,2,1,5]
numsOr = reduce(ior, nums)
Templates
Primes
PRIMES = []
for i in range(2, 1001):
for j in range(2, i):
if not i % j:
break
else:
PRIMES.append(i)
Combination
MOD = 10**9 + 7
MX = 10**5
fac = [0] * MX
fac[0] = 1
for i in range(1, MX):
fac[i] = fac[i - 1] * i % MOD
inv_f = [0] * MX
inv_f[-1] = pow(fac[-1], -1, MOD)
for i in range(MX - 1, 0, -1):
inv_f[i - 1] = inv_f[i] * i % MOD
def comb(n: int, m: int) -> int:
return fac[n] * inv_f[m] * inv_f[n - m] % MOD if 0 <= m <= n else 0