对数字列表进行所有可能的操作组合以查找特定数字
Posted
技术标签:
【中文标题】对数字列表进行所有可能的操作组合以查找特定数字【英文标题】:All possible combinations of operations on list of numbers to find a specific number 【发布时间】:2019-08-06 20:09:43 【问题描述】:我知道还有其他类似我的问题,但唯一的问题是他们获得了列表中所有变量的所有组合,但我想要它以便用户输入想要的数字和他们需要的数字制作所需的数字。这是我的代码:
numbers = []
operators = ['+', '*', '-', '/']
desire = int(input("Enter the number you want: "))
num1 = int(input("Enter First number: "))
num2 = int(input("Enter Second number: "))
num3 = int(input("Enter Third number: "))
num4 = int(input("Enter Fourth number: "))
numbers.append(num1)
numbers.append(num2)
numbers.append(num3)
numbers.append(num4)
但我不知道如何扩展这个
这是代码应该做什么的示例:
说他们要打的号码是24
和
说他们输入的数字是1, 9, 8, 2
输出应该是这样的:
9 - 1 + 8 * 2 = 24
等等……
需要列出所有可能的解决方案
所有的建议都会非常感谢
【问题讨论】:
您需要将所有数字都用于数字,还是也可以使用四个数字的某个子集? @DaichiJameson 你必须使用所有的数字9 - 1 + 8 * 2
和 9 + 8 * 2 - 1
算作不同的组合吗?
@blhsing 是的
【参考方案1】:
您可以使用 itertools 模块中的排列将数字和运算符以所有可能的方式排列到字符串公式中。然后使用 eval() 计算结果。
例如:
from itertools import permutations
numbers = ["1","9","8","2"]
target = 24
operators = ["+","-","*","/"]
for values in permutations(numbers,len(numbers)):
for oper in permutations(operators,len(numbers)-1):
formula = "".join(o+v for o,v in zip([""]+list(oper),values))
if eval(formula) == target: print(formula,"=",target)
[UPDATE1] 如果允许您多次使用同一个运算符(正如您对 1+1+1*8=24 的评论所建议的那样),您将需要使用 combination_with_replacement 来生成更多运算符模式:
from itertools import permutations,combinations_with_replacement
numbers = ["1","1","1","8"]
target = 10
operators = ["+","-","*","/"]
seen = set()
for values in permutations(numbers,len(numbers)):
for operCombo in combinations_with_replacement(operators,len(numbers)-1):
for oper in permutations(operCombo,len(numbers)-1):
formula = "".join(o+v for o,v in zip([""]+list(oper),values))
if formula not in seen and eval(formula) == target:
print(formula,"=",target)
seen.add(formula)
本质上,这与前面的示例的区别仅在于插入了for operCombo in ...
循环。
注意:这些组合将生成看起来完全相同的公式,因此您需要避免打印已经见过的解决方案(就像我在这里所做的那样)。如果在输入中重复任何数字,则在前面的示例中也会出现重复。
还要注意,为了使 9-1+8*2 得到 24,乘法必须在加法和减法之前执行(即在优先规则下),否则 9-1+8*2=32。您需要支持括号以涵盖不同的操作顺序。
[UPDATE2] 支持括号会涉及更多内容,具体取决于您要允许多少个数字。对于 4 个数字,有 11 种模式:
无括号:A+B+C+D A+B组:(A+B)+C+D B+C组:A+(B+C)+D C+D 组:A+B+(C+D) A+B 和 C+D 组:(A+B)+(C+D) A+B+C组:(A+B+C)+D B+C+D 组:A+(B+C+D) A+B组+C:((A+B)+C)+D A+B+C组:(A+(B+C))+D B+C组+D:A+((B+C)+D) B+C+D组:A+(B+(C+D))如果您有超过 4 个数字,则括号分组的模式会更多。
这是一个示例(4 个数字):
from itertools import permutations,combinations_with_replacement
numbers = ["9","8","1","2"]
target = 24
operators = ["+","-","*","/"]
groups = ['X+X+X+X', 'X+X+(X+X)', 'X+(X+X)+X', '(X+X+X)+X', '(X+X)+X+X', 'X+(X+X+X)', '((X+X)+X)+X', 'X+(X+(X+X))', 'X+((X+X)+X)', '(X+X)+(X+X)', '(X+(X+X))+X']
seen = set()
for values in permutations(numbers,len(numbers)):
for operCombo in combinations_with_replacement(operators,len(numbers)-1):
for oper in permutations(operCombo,len(numbers)-1):
formulaKey = "".join(oper+values)
if formulaKey in seen: continue # ignore variations on parentheses alone
for pattern in groups:
formula = "".join(o+p for o,p in zip([""]+list(oper), pattern.split("+")))
formula = "".join(v+p for v,p in zip([""]+list(values),formula.split("X")))
try:
if eval(formula) == target:
print(formula,"=",target)
seen.add(formulaKey)
break
except: pass
分组可能导致除以零,因此必须添加 try:except 块。
这会产生以下结果:
9*8/(1+2) = 24
9+8*2-1 = 24
9*8/(2+1) = 24
9-1+8*2 = 24
9-(1-8*2) = 24
9-1+2*8 = 24
(9-1)*2+8 = 24
9/(1+2)*8 = 24
9/((1+2)/8) = 24
9-(1-2*8) = 24
9+2*8-1 = 24
9/(2+1)*8 = 24
9/((2+1)/8) = 24
8+(9-1)*2 = 24
8*9/(1+2) = 24
8*9/(2+1) = 24
8-(1-9)*2 = 24
8/(1+2)*9 = 24
8/((1+2)/9) = 24
8+2*(9-1) = 24
8*2+9-1 = 24
8*2-1+9 = 24
8/(2+1)*9 = 24
8/((2+1)/9) = 24
8-2*(1-9) = 24
8*2-(1-9) = 24
2*(9-1)+8 = 24
2*8+9-1 = 24
2*8-1+9 = 24
2*8-(1-9) = 24
要为更多数字生成括号分组模式,您可以使用此函数:
from itertools import product
import re
def groupPatterns(count,pattern=None):
arr = pattern or "X"*count
if len(arr) < 2 : return [arr]
result = []
for mid in range(1,len(arr)):
leftPattern = groupPatterns(count,arr[:mid])
rightPattern = groupPatterns(count,arr[mid:])
for left,right in product(leftPattern,rightPattern):
result += [left + right]
if len(left) > 1 : result += ["(" + left + ")" + right]
if len(right) > 1 : result += [left + "(" + right + ")"]
if len(left) > 1 and len(right) > 1:
result += ["(" + left + ")(" + right + ")"]
if pattern: return result # recursion
patterns = [] # final, add "+" between X value placeholders or groups
for pat in sorted(set(result),key=lambda x:len(x)):
pat = re.sub("X(?=X)", r"X+", pat) # XX --> X+X
pat = re.sub("X\(", r"X+(", pat) # X( --> X+(
pat = re.sub("\)X", r")+X", pat) # )X --> )+X
pat = re.sub("\)\(", r")+(", pat) # )( --> )+(
patterns.append(pat)
return patterns
然后将上例中的groups = ["X+X+X+X",...
替换为groups = groupPatterns(len(numbers))
。
或者,为任意数量的值创建一个完全通用的函数,有或没有分组和运算符重用:
from itertools import permutations,combinations_with_replacement
def numbersToTarget(numbers,target,reuseOper=True,allowGroups=True,operators=["+","-","*","/"]):
groups = groupPatterns(len(numbers)) if allowGroups else [ "+".join("X"*len(numbers)) ]
seen = set()
for values in permutations(numbers,len(numbers)):
for operCombo in combinations_with_replacement(operators,len(numbers)-1) if reuseOper else [operators]:
for opers in permutations(operCombo,len(numbers)-1):
formulaKey = str(opers)+str(values)
if formulaKey in seen: continue # ignore variations on parentheses alone
for pattern in groups:
formula = "".join(o+p for o,p in zip([""]+list(opers), pattern.split("+")))
formula = "".join(str(v)+p for v,p in zip([""]+list(values),formula.split("X")))
try:
if eval(formula) == target:
seen.add(formulaKey)
yield formula
break
except: pass
for formula in numbersToTarget([9,8,1,2],24):
print("24 =",formula)
for formula in numbersToTarget([9,8,1,2,5],0,allowGroups=False):
print("0 =",formula)
【讨论】:
这太棒了!让我的尝试感到羞耻? @Alain T. 我将如何添加更多数字来解决? 该函数的第一个参数是一个列表,因此您可以输入任意数量的数字(如上一个示例中所示numbersToTarget([9,8,1,2,6])
。如果您想要多个目标,您可以为每个目标调用该函数在循环中或将目标参数也设为列表并在函数内测试eval(formula) in target
而不是eval(formula) == target
很棒的代码,为什么 3 个数字什么时候没有输出/错误?【参考方案2】:
这是我想出的使用eval()
对数学运算符字符串进行数学评估的方法(请注意,这不是一种非常安全的方法,恶意用户可能会通过它破解您的程序。如果您正在部署,那么也许看看Evaluating a mathematical expression in a string)
numbers = []
operators = ['+', '*', '-', '/']
desire = int(input("Enter the number you want: "))
num1 = input("Enter First number: ")
num2 = input("Enter Second number: ")
num3 = input("Enter Third number: ")
num4 = input("Enter Fourth number: ")
numbers.append(num1)
numbers.append(num2)
numbers.append(num3)
numbers.append(num4)
for operator1 in operators:
for operator2 in operators:
for operator3 in operators:
problem = numbers[0] + operator1 + numbers[1] + operator2 + numbers[2] + operator3 + numbers[3]
result = int(eval(problem))
if result == desire:
print(" = ".format(problem, result))
我的第一个简单测试
Enter the number you want: 40
Enter First number: 10
Enter Second number: 10
Enter Third number: 10
Enter Fourth number: 10
产量
10+10+10+10 = 40
更复杂的测试
Enter the number you want: 18
Enter First number: 6
Enter Second number: 3
Enter Third number: 4
Enter Fourth number: 4
产量:
6*3+4-4 = 18
6*3*4/4 = 18
6*3-4+4 = 18
6*3/4*4 = 18
6/3+4*4 = 18
应该注意的是,此解决方案并未考虑您的号码的各种顺序。我看看我能不能做出更狡猾的东西
更新
我已经设计了一种方法来考虑数字的所有排列
def make_order_combinations():
number_orders = []
for i in range(4):
for j in range(4):
for k in range(4):
for z in range(4):
if i != j and i != k and i != z and j != k and j != z and k != z:
number_orders.append((i, j, k, z))
return number_orders
def solve_given_number_order(number_order):
for operator1 in operators:
for operator2 in operators:
for operator3 in operators:
problem = numbers[number_order[0]] + operator1 + numbers[number_order[1]] + operator2 + numbers[number_order[2]] + operator3 + numbers[number_order[3]]
# print(problem)
result = eval(problem)
# print(result)
if result == desire:
print(" = ".format(problem, result))
numbers = []
operators = ['+', '*', '-', '/']
desire = int(input("Enter the number you want: "))
num1 = input("Enter First number: ")
num2 = input("Enter Second number: ")
num3 = input("Enter Third number: ")
num4 = input("Enter Fourth number: ")
numbers.append(num1)
numbers.append(num2)
numbers.append(num3)
numbers.append(num4)
list_of_orders = make_order_combinations()
for order in list_of_orders:
solve_given_number_order(order)
现在开始测试
Enter the number you want: 67
Enter First number: 15
Enter Second number: 4
Enter Third number: 7
Enter Fourth number: 1
产量
15*4+7*1 = 67
15*4+7/1 = 67.0
15*4+1*7 = 67
15*4*1+7 = 67
15*4/1+7 = 67.0
15*1*4+7 = 67
15/1*4+7 = 67.0
4*15+7*1 = 67
4*15+7/1 = 67.0
4*15+1*7 = 67
4*15*1+7 = 67
4*15/1+7 = 67.0
4*1*15+7 = 67
4/1*15+7 = 67.0
7+15*4*1 = 67
7+15*4/1 = 67.0
7+15*1*4 = 67
7+15/1*4 = 67.0
7+4*15*1 = 67
7+4*15/1 = 67.0
7+4*1*15 = 67
7+4/1*15 = 67.0
7+1*15*4 = 67
7*1+15*4 = 67
7/1+15*4 = 67.0
7+1*4*15 = 67
7*1+4*15 = 67
7/1+4*15 = 67.0
1*15*4+7 = 67
1*4*15+7 = 67
1*7+15*4 = 67
1*7+4*15 = 67
您可以看到它确实考虑了所有可能的数字重新排列。操作顺序仍然适用,因此输出:
1*7+4*15 = 67
应该读作 (1*7)+(4*15) = 67
【讨论】:
它确实有效,但由于某种原因,当我输入:1,1,1,8
它不输出 24,即使解决方案是 1 + 1 + 1 * 8 = 24
,它也不适用于我输入的那个我的问题你知道这是为什么吗?
你的答案和 Alain T. 的答案都是这样做的,只有 hiro 主角的答案由于某种原因不会这样做
您的示例 (9-1+8*2 = 24) 意味着公式必须应用运算符优先级。 1+1+1*8 = 10,当在加法之前执行乘法(根据优先规则)
@system123456 这是因为操作顺序。乘法优先所以 1 + 1 + 1 * 8 -> 1 + 1 + (1 * 8) -> 1 + 1 + 8 -> 10 而不是 24【参考方案3】:
这确实没有经过很好的测试(可能做的工作太多),但可能会让你开始:
from operator import mul, add, sub, truediv
from itertools import permutations, combinations_with_replacement
operators = (mul, add, sub, truediv)
desire = 24
numbers = [1, 9, 8, 2]
OP2SYM = mul: '*', add: '+', sub: '-', truediv: '/'
for op0, op1, op2 in combinations_with_replacement((mul, add, sub, truediv), 3):
for n0, n1, n2, n3 in permutations(numbers, 4):
# print(op0, op1, op2)
# print(n0, n1, n2, n3)
if op0(n0, op1(n1, op2(n2, n3))) == desire:
print(' ( ( ))'.format(
n0, OP2SYM[op0], n1, OP2SYM[op1], n2, OP2SYM[op2], n3))
if op0(op1(n0, n1), op2(n2, n3)) == desire:
print('( ) ( )'.format(
n0, OP2SYM[op0], n1, OP2SYM[op1], n2, OP2SYM[op2], n3))
if op2(op1(op0(n0, n1), n2), n3) == desire:
print('(( ) ) '.format(
n0, OP2SYM[op0], n1, OP2SYM[op1], n2, OP2SYM[op2], n3))
输出
((8 * 2) + 9) - 1
((2 * 8) + 9) - 1
一个更简单的想法是构造'6*3-4+4'
形式的字符串并使用ast.literal_eval
来评估它们
【讨论】:
愿望号码是24
,当我输入1,1,1,8
时,它会输出:8 * (1 + (1 + 1))
6次,你知道为什么吗?
8 , 1, 1, 1
的排列将包含8 , 1, 1, 1
六次; permutations
的 a, b
将包含 b, a
;如果a = b
你会有重复。您可以添加set
(例如称为seen
),然后继续您已经拥有seen
的组合。【参考方案4】:
您可以尝试使用 itertools
中的 permutations 模块from itertools import permutations, combinations
numbers = ""
solutions = []
operators = "+*-/"
desire = int(input("Enter the number you want: "))
num1 = input("Enter First number: ")
num2 = input("Enter Second number: ")
num3 = input("Enter Third number: ")
num4 = input("Enter Fourth number: ")
#concatenate the input
numbers = num1 + num2 + num3 + num4
#generate all possible permutations of this characters
num_permutations = [p for p in permutations(numbers)]
op_combinations = [p for p in combinations(operators,3)]
for n_perm in num_permutations:
for op_perm in op_combinations:
cur_expression = ""
for i in range(3):
cur_expression += n_perm[i] + op_perm[i]
cur_expression += n_perm[3]
tmp_solution = eval(cur_expression)
if desire == tmp_solution:
solutions.append(tmp_solution)
【讨论】:
运行您的代码时出现此错误tmp_solution = eval(cur_expression) TypeError: eval() arg 1 must be a string, bytes or code object
你是对的。我修复了它:cur_expression
是一个列表而不是一个字符串。修复它允许 eval() 运行并计算操作结果
当我输入数字时没有结果出现
显然。我没有使用print()
函数。它旨在让您扩展您正在编写的代码。 solutions 数组将包含产生所需数字的所有字符串。以上是关于对数字列表进行所有可能的操作组合以查找特定数字的主要内容,如果未能解决你的问题,请参考以下文章