Skip to content

Instantly share code, notes, and snippets.

@rumpl
Created December 12, 2010 12:07
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 rumpl/738002 to your computer and use it in GitHub Desktop.
Save rumpl/738002 to your computer and use it in GitHub Desktop.
Try to find the number 26 with 2,3,4,5 and the four basic operations (+,-,/,*)
import math
# Try to find the number 26 with 2,3,4,5 and the four basic operations (+,-,/,*)
def all_perms(str):
if len(str) <= 1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm)+1):
yield perm[:i] + str[0:1] + perm[i:]
def calc(expr):
return eval(expr, dict(__builtins__ = None), {})
def calculate(p):
try:
res = calc(" ".join(p))
if res == 26:
print " ".join(p)
except:
pass
def main():
numbers = ['2.', '3.', '4.', '5.']
all_signs = [['+', '-', '/', '(', ')'], ['+', '-', '*', '(', ')'], ['+', '*', '/', '(', ')'], ['-', '*', '/', '(', ')']]
for signs in all_signs:
d = numbers + signs
for p in all_perms(d):
if p[0] in ['2.', '3.', '4.', '5.', '(']:
calculate(p)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment