Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Last active September 21, 2016 10:08
Show Gist options
  • Save louisswarren/31b72eb70036aa8b41b0ae36090944d4 to your computer and use it in GitHub Desktop.
Save louisswarren/31b72eb70036aa8b41b0ae36090944d4 to your computer and use it in GitHub Desktop.
Co-sane implementations of python builtins and more
import itertools
sum = lambda x: list(itertools.accumulate(x)).pop()
len = lambda x: sum(1 for _ in x)
range = lambda n, step=1: itertools.accumulate(itertools.repeat(step, times=n-1), lambda x, y: x + y)
# Full implementation
range = lambda min, max=None, step=1: itertools.accumulate(itertools.chain((min if max is not None else 0,),
itertools.repeat(step, (max-min-1)//step if max is not None else None)))
# Choose one
product = lambda *x: __import__('functools').reduce(__import__('operator').mul, x, 1)
product = lambda a, b: sum(a for _ in range(b))
product = lambda a, b: sum(itertools.repeat(a, b))
product = lambda a, b: len(itertools.product(range(a), range(b)))
product = lambda *x: len(itertools.product(*(range(y) for y in x)))
# Of course they should all have been lazy
product = lambda *args: 0 if 0 in args else product(*args)
bool = lambda x: True if x else False
all = lambda iterable: product(bool(x) for x in iterable)
any = lambda iterable: sum(bool(x) for x in iterable)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment