Calculator in python

后端 未结 7 983
别那么骄傲
别那么骄傲 2021-01-27 01:45

I am trying to make calculator that can solve expressions with basic 4 operators, like 1+2*3-4/5, however it does not work and I do not know what is wrong. Please check my code.

7条回答
  •  情书的邮戳
    2021-01-27 02:39

    The main thing you are doing wrong is that you are checking the value of c rather that the partitioned operator. You can also unpack the result from s.partition to make things a little easier by using left and right for the actual operations.

    def ret(s):
        s = str(s)
        if s.isdigit():
            return float(s)
        for c in ('-','+','*','/'):
            left, op, right = s.partition(c)
            if op == '*':
                return ret(left) * ret(right)
            elif op == '/':
                return ret(left) / ret(right)
            elif op == '+':
                return ret(left) + ret(right)
            elif op == '-':
                return ret(left) - ret(right)
    print(ret('1+2'))
    

    Also, you will need to reverse the order of your operations as you want to first do addition and subtraction, followed by multiplication and division.

    What I mean is, if you have an expression like 4+4*3, you want to divide it into

    ret(4) + ret(4 * 3)
    

    Since it is a recursive call, you want the operators with the highest precedence to be the last on the call stack so they are executed first when the function returns.

    As an example:

    print(ret('1+2*6'))
    print(ret('3*8+6/2'))
    

    OUTPUT

    13.0
    27.0
    

提交回复
热议问题