# Basic Calculator II in Python

PythonServer Side ProgrammingProgramming

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 < n
• 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 < 0, then update stack top element as -(stack top / num), otherwise update stack top element as (stack top / num)
• 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<n:
if s[i] == '/':
i+=1
num,i = self.make_num(s,i)
if stack[-1]<0:
stack[-1] = -1*(abs(stack[-1])/num)
else:
stack[-1] = stack[-1]/num
elif s[i] == '*':
i+=1
num,i = self.make_num(s,i)
stack[-1] = stack[-1]*num
elif s[i] == '-':
i+=1
num,i = self.make_num(s,i)
stack.append(-num)
elif s[i] =='+':
i+=1
num,i = self.make_num(s,i)
stack.append(num)
else:
num,i = self.make_num(s,i)
stack.append(num)
i+=1
return sum(stack)
def make_num(self,s,i):
start = i
while i<len(s) and s[i]!= '/' and s[i]!= '*' and s[i]!= '-' and s[i]!='+':
i+=1
return int(s[start:i]),i-1

## Input

"3+2*2"

## Output

7