Skip to content

TIL

Dynamic Programming:

  1. Decision Problem
  2. COmbinatorics Problem
  3. Optimization problem

tip

There is a chance for overflow when we are adding to massive numbers so instead of dividing directly by 2 we do either of the 2 following approaches: 1. left + (right-left)/2 2. left + right >>> 1

Notice how we can get the grid range

def is_valid(grid, r, c, k):
    not_in_row = k not in grid[r]
    not_in_columen = k not in [grid[i][c] for i in range(len(grid))]
    not_in_grid = k not in [
        grid[i][j]
        for i in range(r // 3 * 3, r // 3 * 3 + 3)
        for j in range(c / 3 * 3, c // 3 * 3 + 3)
    ]

Nwise

from itertools import islice, tee

nwise = lambda g, *, n=2: zip(*(islice(g, i, None) for i, g in enumerate(tee(g, n))))

More recursion limit

from sys import getrecursionlimit, setrecursionlimit
from contextlib import contextmanager


@contextmanager
def morerecursion():
    prev = getrecursionlimit()
    try:
        setrecursionlimit(2 * prev)
        yield
    finally:
        setrecursionlimit(prev)

Retry

def retry(f):
    def inner(*args, **kwargs):
        for _ in range(3):
            try:
                return f(*args, **kwargs)
            except Exception:
                pass
        ...

    return inner

Fibs

def fib(a=1, b=1):
    while True:
        yield a
        a, b = b, a + b

Python Itertools

count

from itertools import count

for i in count(5):
    print(i)

l = ["a", "b", "c"]
print(list(zip(count(), l)))
# [(0, 'a'), (1, 'b'), (2, 'c')]

cycle

from itertools import cycle

l = [1, 2, 3, 4, 5]
names = ["rohit", "rajat"]

for o in zip(cycle(l), names):
    print(o)

Tee

from itertools import tee

l = [1, 2, 3, 4, 5]

tee(l, 2)
# [1,2,3,4,5],[1,2,3,4,5]

pairwise

from itertools import pairwise

pairwise("ABCDEFG")  # --> AB BC CD DE EF FG

Bit Operations

five major points: 1. And 2. Or 3. Not 4. Xor 5. Left shift 6. Right shift

Left shift

  • 5 << 1 = 10 // 5 * 2**1
  • 5 << 2 = 20 // 5 * 2**2

Right shift

  • 5 >> 1 = 5/2
  • 5 >> 2 = 5/4

XOR

-> XOR of same element is 0

-> XOR with 0 is the number itself.

Unique element

5 15 5 3 5 15 |

One element that repeats

5 1 2 3 4 5 | Do xor twice.

  • Number odd or even?
    • n & 1 -> odd
    • n & 1^1 -> even

Set bit --> in binary representation, number of 1s are called set bit.

  • Find set bit?
    while n>0:
        sum.append(n&1)  
        n>>1
    
  • Check if jth bit is set or not

s = s & (1 << j)

  • to turn on jth bit

s = s | (1 << j)

  • to turn off jth bit

s = s & ~(1 << j)

  • to flip jth bit

s = s ^ (1 << j)