Skip to content

Instantly share code, notes, and snippets.

@rene-armida
Created April 27, 2012 20:37
Show Gist options
  • Save rene-armida/2512852 to your computer and use it in GitHub Desktop.
Save rene-armida/2512852 to your computer and use it in GitHub Desktop.
A solution to Jon Erickson's math puzzle
# http://books.google.com/books?id=0FW3DMNhl1EC&lpg=PA1&ots=tt-xF-JWXq&dq=jon%20erickson%20art%20of%20exploitation%20math%20problem&pg=PA1#v=onepage&q=math%20problem&f=false
#
# Use each of the numbers 1, 3, 4, and 6 exactly once with any of the four basic math operations
# (addition, subtraction, multiplication, and division) to total 24. Each number must be used
# once and only once, and you may define the order of operations; for example, 3 * (4 + 6) + 1 = 31
# is valid, however incorrect, since it doesn't total 24.
from fractions import Fraction
import itertools
def treeify(operators, operands):
if len(operands) == 1:
yield operands[0]
for i, op in enumerate(operators):
for left in treeify(operators[:i], operands[:i+1]):
for right in treeify(operators[i+1:], operands[i+1:]):
yield (left, op, right)
def expr(tree):
return str(tree).replace(',', '').replace('\'', '')
def main():
i_operators = itertools.product(['+', '-', '*', '/'], repeat=3)
i_operands = itertools.permutations(['f1', 'f3', 'f4', 'f6'])
for i in [1, 3, 4, 6]:
globals()['f%s' % i] = Fraction(i)
for operators, operands in itertools.product(i_operators, i_operands):
for tree in treeify(operators, operands):
e = expr(tree)
try:
if eval(e) == 24:
print e.replace('f', '')
except ZeroDivisionError:
pass
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment