列出所有4个随机数(0-9)可以等于10(使用任何运算符+,-,*,/)的方式

问题描述 投票:-3回答:1

我想编写一个程序,将4位数字作为输入(或一个4位数字进行拼接),并找到以不同的方式(+,-,*,/)来等于10的方式进行操作。

一些例子是:

  1. 1548:8-4 + 1 + 5 = 10
  2. 2331:3 * 3 + 2-1 = 10
  3. 2293:(9-3)* 2-2 = 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))

这打印出我认为可以订购数字的所有独特方式:

  1. 1234
  2. 1243
  3. 1324
  4. 1342
  5. 1423
  6. 1432
  7. 2134
  8. 2143
  9. 2314
  10. 2341
  11. 2413
  12. 2431
  13. 3124
  14. 3142
  15. 3214
  16. 3241
  17. 3412
  18. 3421
  19. 4123
  20. 4132
  21. 4213
  22. 4231
  23. 4312
  24. 4321
python math operators
1个回答
0
投票

您可以尝试以下使用productpermutationseval的方法:

# 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)

demo

© www.soinside.com 2019 - 2024. All rights reserved.