编程语言
首页 > 编程语言> > python – 获取RPN树大小

python – 获取RPN树大小

作者:互联网

我已经实现了以下’树大小调整器’但它在某些条件下失败了,当它应该返回大小4时,示例下面返回大小2,任何人都可以帮助我.我已多次写这篇文章但无济于事,它一直都在失败.提前致谢

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

几个例子:
    [‘1′,’1′,”,’1′,’1’,”,”]
    [‘1′,’1′,’1’,”,”]
两者都给出结果为3,这是正确的,但是.
    [‘1′,’1′,”,’1′,’1’,”,”]
当它应该是4时返回3

总而言之,我需要从字符串表示中知道RPN的深度.

解决方法:

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

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

标签:python,tree,genetic-algorithm,genetic-programming,rpn
来源: https://codeday.me/bug/20190627/1307890.html