Code snippets
Category: /templateSome tricks
Convertion
# string <--> int:
ord('a') = 97, chr(97) = 'a'
'0'.isdecimal() == True
# enumeration:
for i in range(2**n, 2**(n+1)):
bitmask = bin(i)[3:] # skip '0b1'
for j in range(n):
if bitmask[j] == '1':
# do some actions
# K largest in heap
count = Counter(nums)
return heapq.nlargest(k, count.keys(), key=count.get)
Initialize a 2-D (M * N) array
rows = len(grid) # M
cols = len(grid[0]) # N
dp = [[-1 for _ in range(cols)] for _ in range(rows)]
Define diagonals
Useful in checking matrix, board games.
-
“dale” diagonals(正斜线 in math
y=-x+b
): in coding,row + column = const
-
“hill” diagonals (反斜线 in math
y=x+b
): in coding,row - column = const
See: LC 52 N-Queens
rows = [0] * n
hills = [0] * (2 * n -1)
dales = [0] * (2 * n -1)
# place
rows[col] = 1
hills[row + col] = 1
dales[row - col] = 1
# remove
rows[col] = 0
hills[row + col] = 0
dales[row - col] = 0
# checking
return not (rows[col] or hills[row + col] or dales[row - col])