首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >给定一个用数学符号分隔整数的列表,找出某个值是否可以通过放置大括号来计算。

给定一个用数学符号分隔整数的列表,找出某个值是否可以通过放置大括号来计算。
EN

Stack Overflow用户
提问于 2022-05-08 09:36:58
回答 2查看 62关注 0票数 0

我试着写一个函数,得到:

  1. 是一个整数。(S)
  2. 用数学符号分隔整数的列表。(L)

通过使用递归来确定是否可以通过放置大括号从列表中计算s的值。有什么解决办法吗?我考虑过使用eval()函数。

例如:l= 6,'-',4,'*',2,'+',3 s=10返回: True,for:(6-4)*(2+3)=10

L= 6,'-',4,'*',2,'+',3 s=1返回: True,True:(6-(4*2))+3=1

L= 6,'-',4,'*',2,'+',3 s=100返回: False,因为没有有效的方法在L中放置大括号,从而得到100的解。

谢谢:)

EN

回答 2

Stack Overflow用户

发布于 2022-05-09 07:14:23

让我们用文字来描述递归,我认为更好的理解,我们只需要准确地定义它所做的,这就像归纳。

rec函数:输入一个数字列表,并返回大括号的所有组合(后面的示例)。

base: list有一个元素,例如3,函数返回(3),这是唯一的组合。或只返回3个元素的列表(2+3)

假设:我们可以对N -2大小的列表进行求解,例如:6,'-',4,'_',2,‘+’,3N= 7,所以我们可以对大小为5 4,'_',2,'+',3的列表进行求解,得到所有的组合:

  1. (4*2) + (3)
  2. (4) * (2+3)

步骤:为N解决它!我们需要做的是检查从rec调用中得到的所有组合(如果我们在N= 7上,它只是示例中的1和2),我们只需要为每个组合做以下事情:将当前数字放在最左边的数字旁边并对其进行操作,或者将它放在大括号前面,并在所有表达式上加大括号,例如:

从选项1我们得到了两个新的选项

6 - ( 4*2) +(3)

(6 - 4*2) +(3)

从选项2我们得到了两个新的选项

(6-4) * (2+3)

6- (4) *(2+3)

现在rec函数返回所有的组合,我们可以对每个组合调用eval来检查结果。

票数 0
EN

Stack Overflow用户

发布于 2022-05-14 17:33:03

下面是完整的应用程序。

适用于任何公式长度。括号给出运算符的顺序,所以我们测试所有的组合。

测试n个运算符的所有排列都是n!

与样本中的3个操作符一样,这是6个测试。

对于8个运营商来说,将是40320 .

当找到搜索的值时,代码不会停止,因为这可能是获得相同结果的几种方式。

最后给出了所有可能的结果。

对于给定的公式:-所有可能的结果:{1,7,10,-14,-5}

尽情享受

代码语言:javascript
运行
复制
from itertools import permutations

formula = [6,'-',4,'*',2,'+',3] ;
searchedValue = 10 ;

# operators are on odd positions . 
operatorsPositions = list(range(1,len(formula),2)) # [1, 3, 5]
# prepare all permutations eq all parenthesis order . return an array of tuple
permut = list(permutations(operatorsPositions))
print("**** {0} permutations to be tested ****".format(len(permut)))
print(permut)


# around an operator , two operands . return result
def calcAround(aFormula,position):
 op1 = aFormula[position -1]
 op2 = aFormula[position +1]
 operator = aFormula[position]
 # optional trace operation
 # print("calculate ({0:2d} {1} {2:2d})".format(op1,operator,op2));
 if (operator == "-"): return op1-op2;
 if (operator == "+"): return op1+op2;
 if (operator == "*"): return op1*op2;
 if (operator == "/"): return op1/op2;
 #--------------------

# 'op1', 'operator', 'op2'  replaced by result in formula
def reduceAtPosition(someformula,position):
    result = calcAround(someformula,position);
    formulaNew =[];
    for i in range (0,position-1): formulaNew.append(someformula[i]);
    formulaNew.append(result);
    for i in range (position+2,len(someformula)):formulaNew.append(someformula[i]);
    return formulaNew;

# ------- main part --------
#  set to store unique possible results 
allResults = set(())
# try each permutation of operators order 
for aTest in permut: 
  aPermut = list(aTest) # better to have an array in place of tuple
  print('----------------')
  # make a new copy each tour 
  lTempo = formula.copy()
  print("operators sequence: {0}".format(aPermut))

  while(len(aPermut)>0):
    print(lTempo)
    anOpIndice = aPermut[0]
    lTempo = reduceAtPosition(lTempo,anOpIndice);
    # remove first done 
    aPermut = aPermut[1:]  
    for i in range(0,len(aPermut)):
      if (aPermut[i]>anOpIndice): aPermut[i] -= 2
  # 
  final = lTempo[0]
  print("result: {0}".format(final))
  # to respond to question 
  if(final == searchedValue): 
    print('*** found {0} with order or operators positions: {1} '.format(final,aTest))
  
  allResults.add(final)
print('---- all possible results : {0}'.format(allResults))

控制台结果:

代码语言:javascript
运行
复制
**** 6 permutations to be tested ****
[(1, 3, 5), (1, 5, 3), (3, 1, 5), (3, 5, 1), (5, 1, 3), (5, 3, 1)]
----------------
operators sequence: [1, 3, 5]
[6, '-', 4, '*', 2, '+', 3]
[2, '*', 2, '+', 3]
[4, '+', 3]
result: 7
----------------
operators sequence: [1, 5, 3]
[6, '-', 4, '*', 2, '+', 3]
[2, '*', 2, '+', 3]
[2, '*', 5]
result: 10
*** found 10 with order or operators positions: (1, 5, 3) 
----------------
operators sequence: [3, 1, 5]
[6, '-', 4, '*', 2, '+', 3]
[6, '-', 8, '+', 3]
[-2, '+', 3]
result: 1
----------------
operators sequence: [3, 5, 1]
[6, '-', 4, '*', 2, '+', 3]
[6, '-', 8, '+', 3]
[6, '-', 11]
result: -5
----------------
operators sequence: [5, 1, 3]
[6, '-', 4, '*', 2, '+', 3]
[6, '-', 4, '*', 5]
[2, '*', 5]
result: 10
*** found 10 with order or operators positions: (5, 1, 3) 
----------------
operators sequence: [5, 3, 1]
[6, '-', 4, '*', 2, '+', 3]
[6, '-', 4, '*', 5]
[6, '-', 20]
result: -14
---- all possible results : {1, 7, 10, -14, -5}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72159736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档