3

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

Chris
  • 704
  • 1
  • 11
  • 32
  • Basically you're asking how to write a parser for mathematical expressions - there are lots of resources about this. – kaya3 Jul 07 '21 at 11:56
  • Funny that I "solved" it by `exec ("result = " + string)` `return int(result)` and it said "No cheating! You are not allowed to use "exec" – Egor Wexler Jul 07 '21 at 11:58
  • I dont know that this works your question but there are 2 special built in function in python called `eval` and `exec` you can give them a try. `eval('expression string')` will evaluate that string as an expression and return a value. Example usage `eval('2 + 5')` returns `7` – berkeebal Jul 07 '21 at 12:01

1 Answers1

3

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.