获取 RPN 树大小

Get RPN tree size

我已经实施了以下 'tree sizer' 但在某些情况下它会失败,下面的示例 returns size 2 而它应该 return size 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','+','+'] ['1','1','1','+','+'] 两者都给出了 3 的结果,这是正确的,但是。 ['1','1','+','1','1','+','+'] returns 3 应该是 4

总而言之,我需要从其字符串表示中了解 RPN 的深度。

好吧,只是做了一点 'cheating' 并使用我的 rpn 中缀转换器来实现相同的目标,如果有人需要,我 post 在这里。

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

谢谢大家!

计算树的深度类似于计算表达式,但运算符计算结果深度而不是结果值:

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