Basic Calculator II in Python

Suppose we have to implement a basic calculator to evaluate a simple expression string. The expression string will hold only non-negative integers, some operators like, +, -, *, / and empty spaces. The integer division should take the quotient part only.

So if the input is like “3+2*2”, then the output will be 7.

To solve this, we will follow these steps −

  • define a stack s, i := 0, x := an empty string
  • for each character j in s
    • if j is not a blank character
      • append j into x
  • s := x, n := length of x
  • while i
  • if s[i] is ‘/’, then
    • increase i by 1
    • num := number starting from ith index, then update i as the last character of the number
    • if stack top element
  • otherwise when s[i] = “*”
    • increase i by 1
    • num := number starting from ith index, then update i as the last character of the number
    • stack top := num * stack top
  • otherwise when s[i] = ‘-’
    • increase i by 1
    • num := number starting from ith index, then update i as the last character of the number
    • insert –num into stack
  • otherwise
    • num := number starting from ith index, then update i as the last character of the number
    • insert num into stack
    • increase i by 1
  • return sum of the elements of the stack
  • Let us see the following implementation to get better understanding −

    Example

    class Solution(object):
       def calculate(self, s):
          """
          :type s: str
          :rtype: int
          """
          stack = []
          i = 0
          x=""
          for j in s:
          if j !=" ":
          x+=j
          s = x
          n = len(s)
          while i

    Input

    "3+2*2"

    Output

    7
    Updated on: 2020-03-04T06:20:53+05:30

    989 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements