how to prioritize operations in ( ) for a python calculator where I am given the input as a string?

Viewed 241

I am completing a kata in code wars.

I am given a string like "2 / 2 + 3 * 4 - 6" or "2 * ( 2 * ( 2 * ( 2 * 1 ) ) )"

I can't figure out how to handle ( ) in the code.

Currently I have:

class Calculator(object):
    def evaluate(self, string):
        # if () in s
        # find most inner ()
        s = string.split()
        while len(s) > 1:
            if ('/' in s or
                '*' in s):
                for i in range(len(s)):
                    if s[i] == '/':
                        s[i] = int(s[i-1]) / int(s[i+1])
                        s.pop(i-1)
                        s.pop(i)
                        break
                    elif s[i] == '*':
                        s[i] = int(s[i-1]) * int(s[i+1])
                        s.pop(i-1)
                        s.pop(i)
                        break
            else:
                for i in range(len(s)):
                    if s[i] == '-':
                        s[i] = int(s[i-1]) - int(s[i+1])
                        s.pop(i-1)
                        s.pop(i)
                        break
                    elif s[i] == '+':
                        s[i] = int(s[i-1]) + int(s[i+1])
                        s.pop(i-1)
                        s.pop(i)
                        break
        return s[0]

which functions great except for strings with ( )

How could I handle them so that it follows proper math rules?

Any suggestion is largely appreciated. [1]: https://www.codewars.com/kata/5235c913397cbf2508000048/train/python

1 Answers

You can search for inner parenthesis, then evaluate their content using your function (this is known as recursion), and repeat so until you have no parentheses left.

Inner parentheses are parentheses with no other parentheses between them.

Related