我已经实现了以下‘树sizer’,但它在某些情况下失败了,下面的示例返回大小2时,它应该返回大小4,谁能帮我解决问题。这封信我写了好几遍了,但没有用,它一直在失败。
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))两个例子:'1','1','+','1‘,'1’,'+‘,'+’都给出了3的结果,这是正确的,但是。'1','1','+','1‘,'1’,'+‘,'+’在应该是4的时候返回3
总之,我需要从RPN的字符串表示中了解RPN的深度。
发布于 2017-03-26 22:28:18
计算树的深度类似于计算表达式,但运算符计算结果深度而不是结果值:
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()发布于 2017-03-26 22:01:02
嗯,只是做了一点‘作弊’,并使用我的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谢谢大家!
https://stackoverflow.com/questions/42983364
复制相似问题