Skip to content

Instantly share code, notes, and snippets.

@scturtle
Created October 26, 2012 12:42
Show Gist options
  • Save scturtle/3958553 to your computer and use it in GitHub Desktop.
Save scturtle/3958553 to your computer and use it in GitHub Desktop.
calc24
# coding: utf-8
from __future__ import division
import itertools
exp_list = ['((%d{}%d){}%d){}%d', '(%d{}%d){}(%d{}%d)',
'(%d{}(%d{}%d)){}%d', '%d{}((%d{}%d){}%d)',
'%d{}(%d{}(%d{}%d))']
op_list = list(itertools.product('+ - * /'.split(), repeat=3))
def calc(lst):
for n in itertools.permutations(lst,4):
for ex,op in itertools.product(exp_list, op_list):
exp = ex.format(*op) % n
try:
if eval(exp)==24:
return exp
except:pass
return None
if __name__ == '__main__':
print calc([5,6,7,8]), '= 24'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment