Created
December 12, 2010 12:07
-
-
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 (+,-,/,*)
This file contains hidden or 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
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