from itertools import * import sys, traceback def makeproblem(nums, ops): prob='(('+nums[0]+ops[0]+nums[1]+')'+ops[1]+nums[2]+')'+ops[2]+nums[3] return prob def makeproblem2(nums, ops): prob='('+nums[0]+ops[0]+nums[1]+')'+ops[1]+'('+nums[2]+ops[2]+nums[3]+')' return prob #Cleans up the appearance of the output by removing all ".0" endings from numbers def removedecimals(problem): problem=list(problem) tobepopped=[] for i in range(0, len(problem)): if problem[i]=="." and problem[i+1]=='0': tobepopped.append(i) tobepopped.append(i+1) tobepopped.reverse() for k in tobepopped: problem.pop(k) newproblem="" for j in problem: newproblem+=j return newproblem def getnums(): nums=[] while nums==[]: try: print("Enter four numbers, separated by return.") a=raw_input() if a=="quit": exit() a=float(a) b=float(raw_input()) c=float(raw_input()) d=float(raw_input()) nums=[a,b,c,d] except ValueError: print #spacer print("There was a problem with your entry. Please try again from the beginning.") print #spacer nums=[] stringnums=[] for i in nums: stringnums.append(str(i)) nums=stringnums return nums #Operation permutation list. opperms=list(set(permutations(['+','-','*','/','+','-','*','/','+','-','*','/'], 3))) print '''Welcome to the Solution Finder for the game "24." All "24" problems from the original game can be solved as a series of three equations, each using the answer to the previous equation as input for the next equation This program finds all solutions of that type, as well as the other possible basic type, in which two expressions are combined to make a third expression that equals 24. ''' while True: nums=getnums() #Number permutation list. numperms=list(permutations(nums)) numperms=list(set(numperms)) #problist is the list of solution problems problist=[] for i in numperms: for j in opperms: currentprob=makeproblem(i,j) try: if eval(currentprob)==24: currentprob=removedecimals(currentprob) if currentprob not in problist: problist.append(currentprob) currentprob=makeproblem2(i,j) if eval(currentprob)==24: currentprob=removedecimals(currentprob) if currentprob not in problist: problist.append(currentprob) except ZeroDivisionError: pass if problist==[]: print "No solution." else: if len(problist)==1: print("The solution is:") if len(problist)>1: print("The solutions are:") for k in problist: print(k) print #spacer
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question