Skip to content

Instantly share code, notes, and snippets.

@Rhomboid
Last active December 10, 2015 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rhomboid/4454380 to your computer and use it in GitHub Desktop.
Save Rhomboid/4454380 to your computer and use it in GitHub Desktop.
Find all mathematical combinations
from __future__ import division
ops = [ lambda a, b: (a[0] + b[0], '({} + {})'.format(a[1], b[1])),
lambda a, b: (a[0] * b[0], '({} * {})'.format(a[1], b[1])),
lambda a, b: (a[0] - b[0], '({} - {})'.format(a[1], b[1])),
lambda a, b: (b[0] - a[0], '({} - {})'.format(b[1], a[1])),
lambda a, b: (a[0] / b[0] if b[0] else float('inf'), '({} / {})'.format(a[1], b[1])),
lambda a, b: (b[0] / a[0] if a[0] else float('inf'), '({} / {})'.format(b[1], a[1])) ]
def _combo(S):
if len(S) == 2:
for o in ops:
yield o(S[0], S[1])
else:
for i in range(len(S)):
for rest in _combo(S[:i] + S[i+1:]):
for o in ops:
yield o(S[i], rest)
def find_solutions(numbers, result):
for n, expr in sorted(c for c in _combo([(n, str(n)) for n in numbers]) if c[0] == result):
print expr, '=', result
find_solutions([12, 6, 27], 33)
find_solutions([35, 22, 4, 7, 16], 100)
find_solutions([10, 29, 39, 48, 19], 40)
((12 + 27) - 6) = 33
(12 + (27 - 6)) = 33
(12 - (6 - 27)) = 33
(27 + (12 - 6)) = 33
(27 - (6 - 12)) = 33
(((35 + (22 * 4)) - 16) - 7) = 100
(((35 + (22 * 4)) - 7) - 16) = 100
((35 + ((22 * 4) - 16)) - 7) = 100
((35 + ((22 * 4) - 7)) - 16) = 100
((35 - (16 - (22 * 4))) - 7) = 100
((35 - (7 - (22 * 4))) - 16) = 100
(16 * ((22 - (35 / 4)) - 7)) = 100
(16 * (22 - (7 + (35 / 4)))) = 100
(35 + (((22 * 4) - 16) - 7)) = 100
(35 + (((22 * 4) - 7) - 16)) = 100
(35 - (16 + (7 - (22 * 4)))) = 100
(35 - (16 - ((22 * 4) - 7))) = 100
(35 - (7 + (16 - (22 * 4)))) = 100
(35 - (7 - ((22 * 4) - 16))) = 100
(4 + (16 * ((35 - 22) - 7))) = 100
(4 + (16 * ((35 - 7) - 22))) = 100
(4 + (16 * (35 - (22 + 7)))) = 100
(4 - (16 * ((22 + 7) - 35))) = 100
(4 - (16 * (22 + (7 - 35)))) = 100
(4 - (16 * (22 - (35 - 7)))) = 100
(4 - (16 * (7 + (22 - 35)))) = 100
(4 - (16 * (7 - (35 - 22)))) = 100
((39 + (19 * (48 - 29))) / 10) = 40
((39 - (19 * (29 - 48))) / 10) = 40
((48 + ((39 + 19) / 29)) - 10) = 40
(48 + (((39 + 19) / 29) - 10)) = 40
(48 - (10 - ((39 + 19) / 29))) = 40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment