我已经实施了以下'树大小的'但它在某些条件下失败,下面的示例返回大小2时它应该返回大小4,任何人都可以帮助我。我已多次写这篇文章但无济于事,它一直都在失败。提前致谢
JC
def getRPNdepth(expression):
treesize=0
maxtreesize=treesize
mintreesize=treesize
tmpexp=expression
tmpfmla = [1 if n[0] == 'x' else n for n in tmpexp]
print(tmpfmla)
try:
stack = []
for val in tmpfmla:
if val in ['-', '+', '*', '/']:
op1 = stack.pop()
op2 = stack.pop()
if val == '-': result = op2 - op1
if val == '+': result = op2 + op1
if val == '*': result = op2 * op1
if val == '/':
if op1 == 0:
result = 1
else:
result = op2 / op1
stack.append(result)
treesize=treesize+1
else:
stack.append(float(val))
treesize = treesize - 1
if treesize>maxtreesize:
maxtreesize=treesize
if treesize<mintreesize:
mintreesize=treesize
return abs(mintreesize)
except:
print('error validate rpn>' + str(expression))
return 0
xxxx = ['x6', 'x7', '+', 'x7', '+', 'x7', '+', 'x7', '+']
print(getRPNdepth(xxxx))
几个例子: [&#39; 1&#39;&#39; 1&#39; &#39; +&#39;&#39; 1&#39;&#39; 1&#39; &#39; +&#39; &#39; +&#39;] [&#39; 1&#39;&#39; 1&#39;&#39; 1&#39; &#39; +&#39; &#39; +&#39;] 两者都给出结果为3,这是正确的,但是。 [&#39; 1&#39;&#39; 1&#39; &#39; +&#39;&#39; 1&#39;&#39; 1&#39; &#39; +&#39; &#39; +&#39;] 它应该是4
时返回3总而言之,我需要从字符串表示中知道RPN的深度。
答案 0 :(得分:3)
计算树深度与评估表达式类似,但运算符计算结果深度而不是结果值:
def getRPNdepth(expression):
stack = []
for val in expression:
if val in ['-', '+', '*', '/']:
stack.append(max(stack.pop(),stack.pop())+1)
else:
stack.append(1)
return stack.pop()
答案 1 :(得分:0)
好吧,只是做了一些'作弊'并使用我的rpn到中缀转换器来实现相同的目标,如果有人需要它我在这里发布。
def getRPNdepth(expression):
tmpexp = expression
tmpfmla = [1 if n[0] == 'x' else n for n in tmpexp]
stack = []
for val in tmpfmla:
if val!=' ':
if val in ['-', '+', '*', '/']:
op1 = stack.pop()
op2 = stack.pop()
stack.append('(' + str(op1) + str(val) + str(op2) + ')')
else:
stack.append(str(val))
openparentesiscount=0
maxopenparentesiscount = 0
onlyparentesis=''
for c in stack[0]:
if c in ['(', ')']:
onlyparentesis=onlyparentesis+c
if c=='(':
openparentesiscount=openparentesiscount+1
else:
openparentesiscount = openparentesiscount - 1
if openparentesiscount>maxopenparentesiscount:
maxopenparentesiscount=openparentesiscount
return maxopenparentesiscount
全部谢谢!