Get RPN Tree Size

I implemented the following "tree sizer", but under certain conditions it fails, the example below returns size 2, when it should return size 4, can anyone help me. I wrote this several times, to no avail, she continues to fail. thanks in advance

x

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

some examples: ['1', '1', '+', '1', '1', '+', '+'] ['1', '1', '1', '+', ' + '] both give the result 3, true, but. ['1', '1', '+', '1', '1', '+', '+'] returns 3 when it should be 4

In general, I need to know the depth of the RPN from its string representation.

+4
2

, :

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

, "" 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

!

0

Source: https://habr.com/ru/post/1673039/


All Articles