def jogo_24(numeros):
if len(numeros) == 1:
if abs(numeros[0] - 24) < 1e-6:
return True, [str(numeros[0])]
else:
return False, []
for i in range(len(numeros)):
for j in range(len(numeros)):
if i != j:
a = numeros[i]
b = numeros[j]
novos_numeros = []
for k in range(len(numeros)):
if k != i and k != j:
novos_numeros.append(numeros[k])
operacoes_possiveis = [
lambda x, y: (f"({x} + {y})", x + y),
lambda x, y: (f"({x} - {y})", x - y),
lambda x, y: (f"({y} - {x})", y - x),
lambda x, y: (f"({x} * {y})", x * y),
lambda x, y: (f"({x} / {y})", x / y) if y != 0 else (None, None),
lambda x, y: (f"({y} / {x})", y / x) if x != 0 else (None, None)
]
for operacao in operacoes_possiveis:
resultado_str, resultado = operacao(a, b)
if resultado is not None:
novos_numeros.append(resultado)
encontrou_solucao, solucao = jogo_24(novos_numeros)
if encontrou_solucao:
solucao.insert(0, resultado_str)
return True, solucao
novos_numeros.pop()
return False, []
def solicitar_numeros():
numeros = []
for i in range(4):
numero = float(input(f"Digite o número {i + 1}: "))
numeros.append(numero)
return numeros
print("Bem-vindo ao Jogo do 24!")
numeros = solicitar_numeros()
encontrou_solucao, solucao = jogo_24(numeros)
if encontrou_solucao:
print("É possível formar 24!")
print("Solução:", " ".join(map(str, solucao)))
else:
print("Não é possível formar 24.")