Skip to content

Instantly share code, notes, and snippets.

@fcicq
Created October 31, 2012 09:56
Show Gist options
  • Save fcicq/3986170 to your computer and use it in GitHub Desktop.
Save fcicq/3986170 to your computer and use it in GitHub Desktop.
reduce with midstate preserved
def midreduce_iter(func, d, init=None):
it = iter(d)
if init is None:
i = it.next()
yield i
else:
i = init
while True:
i = func(i, it.next()) # as it will raise StopIteration exception...
yield i
# reduce with midstate preserved
# midreduce(lambda x,y: x+y, [1] * 8) = [1,2,3,4,5,6,7,8]
def midreduce(func, d, init=None):
return list(midreduce_iter(func, d, init))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment