Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
re: [Creative- Although the process is documented, the regex is not...] solution in Creative category for Sum Consecutives by ale1ster
from re import sub, finditer
def sum_consecutives(it):
#.. Does NOT work with general iterables, only lists.
#1. Take the string representation of the list.
#2. Substitute element separators with a single space (not strictly necessary)
#3. Pattern match for all consecutive identical numbers, and group them
#4. Substitute the spaces in the groups with '+'
#5. Evaluate each group (which is of the form 'n+...+n'
#6. Return an iterator of the resulting values
return (eval(sub(r'\s', r'+', m.group('consec'))) for m in \
finditer(r'''(?x)
(?P
(?P -? [0-9]+ )
(?: \s (?P=num) )*
)''', \
sub(r'\s*,\s*', r' ', str(it))))
Nov. 9, 2019