Skip to content

Instantly share code, notes, and snippets.

@apua
Created March 2, 2023 12:02
Show Gist options
  • Save apua/c4bf1bc5b241556058412b4efd54266d to your computer and use it in GitHub Desktop.
Save apua/c4bf1bc5b241556058412b4efd54266d to your computer and use it in GitHub Desktop.
r"""
Ref: https://www.pttweb.cc/bbs/Python/M.1398877470.A.1E7
>>> data = list(range(22)); seglen = 4
>>> list(map(lambda E,T=[0]:T.__setitem__(0,E[1]+(E[0]%seglen and T[0])) or T[0], enumerate(data)))
[0, 1, 3, 6, 4, 9, 15, 22, 8, 17, 27, 38, 12, 25, 39, 54, 16, 33, 51, 70, 20, 41]
>>> x = []
>>> for i, v in enumerate(data):
... x.append(v+x[i-1] if i%seglen!=0 else v)
...
>>> x
[0, 1, 3, 6, 4, 9, 15, 22, 8, 17, 27, 38, 12, 25, 39, 54, 16, 33, 51, 70, 20, 41]
>>> def f(xs, count=0, ys=()):
... if not xs:
... return ys
... else:
... return f(xs[1:], (count+1)%seglen, ys+(xs[0]+(0 if count==0 else ys[-1]),))
...
>>> f(data)
(0, 1, 3, 6, 4, 9, 15, 22, 8, 17, 27, 38, 12, 25, 39, 54, 16, 33, 51, 70, 20, 41)
>>> from itertools import chain
>>> def g(xs, count=0, ys=(), last=0):
... try:
... x = next(xs)
... y = x + (0 if count==0 else last)
... yield from g(xs, (count+1)%seglen, chain(ys, (y,)), y)
... except StopIteration:
... yield from ys
...
>>> tuple(g(iter(data)))
(0, 1, 3, 6, 4, 9, 15, 22, 8, 17, 27, 38, 12, 25, 39, 54, 16, 33, 51, 70, 20, 41)
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment