Skip to content

Instantly share code, notes, and snippets.

@vm
Created February 29, 2016 01:49
Show Gist options
  • Save vm/9bac117a2cbbb1ade55d to your computer and use it in GitHub Desktop.
Save vm/9bac117a2cbbb1ade55d to your computer and use it in GitHub Desktop.
def accumulate_with_remainder(xs):
"""implements accumulate while also returning the remainder
>>> accumulate_with_remainder([1,2,3])
[
([], [1,2,3]),
([1], [2,3]),
([1,2], [3]),
([1,2,3], [])
]
:param xs: list to accumulate
:type xs: list
:returns: list of (accumulated elements, remaining elements)
:rtype: list of (iterable, iterable)
"""
return [split_at(i, xs) for i in range(len(xs)+1)]
def split_at(i, xs):
"""splits xs at i
>>> split_at(2, [1, 2, 3, 4, 5])
([1, 2, 3], [4, 5])
:param i: index to split at
:type i: int
:param xs: list to split
:type xs: list
:returns: first i elements, remaining elements
:rtype: (list, list)
"""
return xs[:i], xs[i:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment