Skip to content

Instantly share code, notes, and snippets.

@mkpoli
Created September 7, 2022 12:47
Show Gist options
  • Select an option

  • Save mkpoli/e85aa3d09d79e8b4c9da0019c04de7bc to your computer and use it in GitHub Desktop.

Select an option

Save mkpoli/e85aa3d09d79e8b4c9da0019c04de7bc to your computer and use it in GitHub Desktop.
God knows why somewhat more efficient way of extending Subset Sum Problem to broadcasted sum of 2d vectors in Python
from functools import reduce
from itertools import combinations
from operator import add
array = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 0, 1)]
target = (1, 1, 1)
def broadcast_sum(*args: tuple[int, ...]) -> tuple[int, ...]:
return reduce(lambda a, b: tuple(map(add, a, b)), args, (0,) * len(args[0]))
result = [tuple(idx) for i in range(1, len(array) + 1) for seq, idx in zip(combinations(array, i), combinations(range(0, len(array), 1), i)) if broadcast_sum(*seq) == target]
print(result) # [(1, 3), (0, 1, 2)]
print(len(result)) # 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment