Skip to content

Instantly share code, notes, and snippets.

@kachayev
Created May 2, 2021 02:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kachayev/717d70e0683a9a63e9ab50376c5eda7a to your computer and use it in GitHub Desktop.
Save kachayev/717d70e0683a9a63e9ab50376c5eda7a to your computer and use it in GitHub Desktop.
Efficient Divide-and-Conquer using compression over little endian
from functools import reduce
from itertools import compress
from operator import mul
def iterate(f, initial):
"""Keeps applying function `f` to accumulated state, yielding each intermediate result.
E.g. iterate(lambda k: k*k, 2) -> 2,4,16,64,256,65536,..."""
state = initial
while True:
yield state
state = f(state)
def little_endian(n):
"""Generates bit in a little-endian order, e.g. little_endian(8) -> [0,0,0,1]"""
state = n
while state > 0:
yield state % 2
state = state // 2
In [1]: 2 ** 8
Out[1]: 256
In [2]: reduce(mul, compress(iterate(lambda k: k*k, 2), little_endian(8)), 1)
Out[2]: 256
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment