Skip to content

Instantly share code, notes, and snippets.

@gdetrez
Created July 25, 2019 16:51
Show Gist options
  • Save gdetrez/257b871383c5924961406fbe821b67a6 to your computer and use it in GitHub Desktop.
Save gdetrez/257b871383c5924961406fbe821b67a6 to your computer and use it in GitHub Desktop.
def sum(xs):
def aux(xs):
try:
x = next(xs)
return x + aux(xs)
except StopIteration:
return 0
return aux(iter(xs))
assert sum([]) == 0
assert sum((1, 2, 3)) == 6
assert sum(range(10)) == 45
def fancy_sum(xs):
from functools import reduce
from operator import add
return reduce(add, xs, 0)
assert fancy_sum([]) == 0
assert fancy_sum((1, 2, 3)) == 6
assert fancy_sum(range(10)) == 45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment