Skip to content

Instantly share code, notes, and snippets.

@aib
Created March 1, 2020 18:52
Show Gist options
  • Save aib/5a9d4171c01ec0b6e2062eb65e6fee7f to your computer and use it in GitHub Desktop.
Save aib/5a9d4171c01ec0b6e2062eb65e6fee7f to your computer and use it in GitHub Desktop.
Should help with a certain type of mathematical puzzles
import functools
import itertools
import operator
def groupings(sum_):
if sum_ == 0:
return [()]
else:
return [(i,) + subg for i in range(1, sum_ + 1) for subg in groupings(sum_ - i)]
groupings_with_length = lambda s, l: list(filter(lambda g: len(g) == l, groupings(s)))
def assign_elements(grouping, elements, fold_op=operator.add):
element_gen = iter(elements)
return tuple(functools.reduce(fold_op, itertools.islice(element_gen, g)) for g in grouping)
assign_digits = functools.partial(assign_elements, fold_op=lambda x, y: x*10 + y)
assert list(groupings(4)) == [(1, 1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 3), (2, 1, 1), (2, 2), (3, 1), (4,)]
assert list(groupings_with_length(6, 3)) == [(1, 1, 4), (1, 2, 3), (1, 3, 2), (1, 4, 1), (2, 1, 3), (2, 2, 2), (2, 3, 1), (3, 1, 2), (3, 2, 1), (4, 1, 1)]
assert assign_elements((2, 1, 3, 4), "abcdefghij") == ("ab", "c", "def", "ghij")
assert assign_digits((1, 3, 1, 4), [1,2,3,4,5,6,7,8,9]) == (1, 234, 5, 6789)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment