Anonymous user
24 game/Solve: Difference between revisions
→{{header|Python}}: Updated to also find solutions involving two sets of brackets
(→{{header|Tcl}}: Make the code only report the first solution by default) |
(→{{header|Python}}: Updated to also find solutions involving two sets of brackets) |
||
Line 15:
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
An answer of "
An answer of "?" will compute an expression for the current digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Line 32 ⟶ 33:
import random, ast, re
import sys
if sys.version_info[0] < 3:
Line 39:
else:
from itertools import zip_longest
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def ask4():
'get four random digits >0 from the plaayer'
digits = ''
while len(digits) != 4 or not all(d in '123456789' for d in digits):
digits = input('Enter the digits to solve for: ')
digits = ''.join(digits.strip().split())
return list(digits)
def welcome(digits):
Line 61 ⟶ 70:
def solve(digits):
>>>
Solution found: 2 + 3 * 6 + 4
'2 + 3 * 6 + 4'
▲ >>> solve(list('4788'))
Solution found: ( 4 + 7 - 8 ) * 8
'( 4 + 7 - 8 ) * 8'
Solution found: ( 2 + 2 * 3 ) * 3▼
▲ '( 2 + 2 * 3 ) * 3'
No solution found for: 1 1 1 1
'!'
Solution found: 1 + 2 + 3 * ( 4 + 5 ) - 6
'1 + 2 + 3 * ( 4 + 5 ) - 6'
>>> """▼
'( 1 + 2 ) * ( 1 + 7 )'
digilen = len(digits)
# length of an exp without brackets
Line 86 ⟶ 94:
opcomb = list(product('+-*/', repeat=digilen-1))
# All the bracket insertion points:
brackets = ( [()] + [(x,y)
for x in range(0, exprlen, 2)
for y in range(x+4, exprlen+2, 2)
if (x,y) != (0,exprlen+1)]
+ [(0, 3+1, 4+2, 7+3)] ) # double brackets case
for d in digiperm:
for ops in opcomb:
Line 95 ⟶ 104:
for b in brackets:
exp = ex[::]
exp.insert(
txt = ''.join(exp)
try:
Line 121 ⟶ 129:
chk = check(answer, digits)
if answer == '?':
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
print ("\nNew digits:", ' '.join(digits))
continue
if answer == '!!':
digits = ask4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if not chk:
|