Created
October 26, 2012 12:42
-
-
Save scturtle/3958553 to your computer and use it in GitHub Desktop.
calc24
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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