Skip to content

Instantly share code, notes, and snippets.

@mihaip
Created January 2, 2014 06:33
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 mihaip/8215718 to your computer and use it in GitHub Desktop.
Save mihaip/8215718 to your computer and use it in GitHub Desktop.
List all (12416) expressions that can be writen while using up all of the pieces in Max's number foam pad (digits 0 to 9, plus, minus and equal signs)
_DIGITS = frozenset(xrange(0, 10))
def generate(sequence, available_digits):
if not available_digits:
yield sequence
for digit in available_digits:
for s in generate(sequence + [digit], available_digits - set((digit, ))):
yield s
def eval(digits):
if digits[0] == 0:
return None
result = 0
for i, d in enumerate(digits):
result += d * pow(10, len(digits) - i - 1)
return result
for digits in generate([], _DIGITS):
for r0 in xrange(1, 8):
t0 = eval(digits[0:r0])
if t0 is None:
continue
for r1 in xrange(r0 + 1, 9):
t1 = eval(digits[r0:r1])
if t1 is None:
continue
for r2 in xrange(r1 + 1, 10):
t2 = eval(digits[r1:r2])
if t2 is None:
continue
t3 = eval(digits[r2:])
if t3 is None:
continue
if t0 + t1 - t2 == t3:
print "%d + %d - %d = %d" % (t0, t1, t2, t3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment