我想编写一个程序,将4位数字作为输入(或一个4位数字进行拼接),并找到以不同的方式(+,-,*,/)来等于10的方式进行操作。
一些例子是:
您必须使用每个数字,但只能使用一次。
因此在示例3中,由于您没有使用6,所以您将无法执行3-2 + 9 = 10而在示例2中,您不能执行3 + 3 + 3 + 1 = 10,因为您只能使用两个3's
为了解决这个问题,我首先找到了可以对数字序列进行排序的每种方式。因此有4个循环(a,b,c,d),当a,b,c或d相等时跳过。
但是,我不确定如何将这些数字放置在不同的基本运算符上,以覆盖所有可能的排列。
在我的脑海中,我将编写一个函数findSolution(x1,x2,x3,x4),该函数返回类似于此的字符串列表=>“(x1 + x2)/ x3 * x4”]
----编辑----要求的代码:
for a in range(1,5):
for b in range(1,5):
if a != b:
for c in range(1,5):
if a != b and a != c and b != c:
for d in range(1,5):
if a != b and a != c and b != c and a != d and b != d and c != d:
print(str(a) + str(b) + str(c) + str(d))
这打印出我认为可以订购数字的所有独特方式:
您可以尝试以下使用product,permutations和eval的方法:
# cook your code here
from itertools import product
from itertools import permutations
operatorList = list(product(['+','-','*','/'], repeat = 3))
ip=['1541','2331','2293']
#operandList=list(permutations(['2','3','3','1'],4))
result=set()
for opertion in operatorList:
for i in ip:
operandList=list(permutations(i,4))
for operand in operandList:
evlStr=operand[0]+opertion[0]+operand[1]+opertion[1]+operand[2]+opertion[2]+operand[3]
if eval(evlStr)==10:
result.add(evlStr)
for i in result:
print (i)