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 "?!!" will computeask an expressionyou for thea new set of currentfour digits.
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):
"""'''\
>>> solve(list(for digits in '3246 4788 1111 123456 1127'.split()):
>>> solve(list('4788'digits))
 
'( 2 + 2 * 3 ) * 3'
Solution found: 2 + 3 * 6 + 4
'2 + 3 * 6 + 4'
>>> solve(list('4788'))
Solution found: ( 4 + 7 - 8 ) * 8
'( 4 + 7 - 8 ) * 8'
>>> solve(list('3322'))
Solution found: ( 2 + 2 * 3 ) * 3
'( 2 + 2 * 3 ) * 3'
>>> solve(list('1111'))
No solution found for: 1 1 1 1
'!'
>>> solve(list('123456'))
Solution found: 1 + 2 + 3 * ( 4 + 5 ) - 6
'1 + 2 + 3 * ( 4 + 5 ) - 6'
Solution found: ( 21 + 2 ) * 3( )1 *+ 37 )
>>> """
'( 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[::]
iffor insertpoint, bracket in zip(b, '()'*(len(b)//2)):
exp.insert(b[0]insertpoint, '('bracket)
exp.insert(b[1], ')')
txt = ''.join(exp)
try:
Line 121 ⟶ 129:
chk = check(answer, digits)
if answer == '?':
answer = solve(digits)
breakanswer = '!'
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
printtrial ("New= digits:", ' '.join(digits))0
print ("\nNew digits:", ' '.join(digits))
continue
if answer == '!!':
digits = ask4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if not chk:
Anonymous user