Created
May 2, 2021 02:40
-
-
Save kachayev/717d70e0683a9a63e9ab50376c5eda7a to your computer and use it in GitHub Desktop.
Efficient Divide-and-Conquer using compression over little endian
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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