Created
March 1, 2020 18:52
-
-
Save aib/5a9d4171c01ec0b6e2062eb65e6fee7f to your computer and use it in GitHub Desktop.
Should help with a certain type of mathematical puzzles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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