Мне нравится решение Саньяша, но я думаю, что это можно сделать более элегантно, используя комбинации операндов и перестановок, пока не будет найдено первое с правильным значением:
from itertools import chain, permutations, combinations
def powerset(iterable):
xs = list(iterable)
return chain.from_iterable(combinations(xs, n) for n in range(len(xs) + 1))
def get_first_perm_with_value(operands, operators, expected_value):
if len(operands) == 0 or len(operands) == 0:
return []
all_operators = list(map(list, permutations(operators, len(operands) - 1)))
all_operands = list(map(list, permutations(operands, len(operands))))
for operator in all_operators:
for operand in all_operands:
result = [""] * (len(operand) + len(operator))
result[::2] = operand
result[1::2] = operator
eq = ''.join(result)
if int(eval(eq)) == expected_value:
return [(f'{eq}={expected_value}', operands)]
return []
lst_expr = []
for operands in map(list, powerset(['1', '2', '3', '10'])):
lst_expr += get_first_perm_with_value(operands, ['+','-','*','/'], 6)
print(lst_expr)
Возвращает:
[('2*3=6', ['2', '3']), ('2*3/1=6', ['1', '2', '3']), ('1+10/2=6', ['1', '2', '10']), ('2*10/3=6', ['2', '3', '10']), ('2*3+1/10=6', ['1', '2', '3', '10'])]