title: Evaluate mathematical expression from String - Python
body: <p>I need to evaluate an expression from a string given such as "(19 + ((91 -96)-13))" but I have to make te algorithm myself, which I can't use eval() or something similar.</p>
  
  <p>I've been tried alot with this code but it gives me problems with negative numbers: </p>
  
  <pre><code>while counter &lt; 1:
      chunks = []
      counter2 = 1
  
      for character in operation:
          if character.isdigit():
              if chunks[-1].isdigit():   # If the last chunk is already a number
                  chunks[-1] += character  # Add onto that number
              else:
                  chunks.append(character) # Start a new number chunk
          elif character in '+-/*()':
              chunks.append(character)  # This doesn't account for `1 ++ 2`.
  
      for e in reversed(chunks):
          if e == '(':
              counter2 = len(chunks) - counter2
              break
          else:
              counter2 = counter2 + 1
  
      if chunks[counter2+2] == '+':
          result2 = int (chunks[counter2+1]) + int (chunks[counter2+3])
      elif chunks[counter2+2] == '-':
          result2 = int (chunks[counter2+1]) - int (chunks[counter2+3])
      elif chunks[counter2+2] == '*':
          result2 = int (chunks[counter2+1]) * int (chunks[counter2+3])
      elif chunks[counter2+2] == '/':
          result2 = int (chunks[counter2+1]) / int (chunks[counter2+3])
  
  
      chunks[counter2] = ''
      chunks[counter2 + 1] = ''
      chunks[counter2 + 2] = str (result2)
      chunks[counter2 + 3] = ''
      chunks[counter2 + 4] = ''
  
      operation = ''.join(chunks)
  </code></pre>
  
  <p>Don't pay attention to the while condition, I'm updating it as I need just to check</p>