8000 added calculateII.py Basic Calculator II · 0ff5ec/Programming@1c25224 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1c25224

8000 Browse files
committed
added calculateII.py Basic Calculator II
1 parent fdba97e commit 1c25224

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

calculateII.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# -*- coding: utf-8 -*-
2+
'''
3+
Implement a basic calculator to evaluate a simple expression string.
4+
5+
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
6+
7+
You may assume that the given expression is always valid.
8+
9+
Some examples:
10+
"3+2*2" = 7
11+
" 3/2 " = 1
12+
" 3+5 / 2 " = 5
13+
Note: Do not use the eval built-in library function.
14+
'''
15+
"""
16+
:type s: str
17+
:rtype: int
18+
"""
19+
class Solution:
20+
def calculate(self, s):
21+
opList, x, operator = [], 0, None
22+
for i in (s + '+'):
23+
if ord('0') - 1 < ord(i) < ord('9') + 1:
24+
x = x * 10 + ord(i) - ord('0')
25+
elif i != ' ':
26+
if operator == '-': x *= -1
27+
elif operator == '*': x *= opList.pop()
28+
elif operator == '/': x = int(opList.pop() * 1.0 / x)
29+
operator = i
30+
opList.append(x)
31+
x = 0
32+
return sum(opList)
33+
34+
if __name__ == "__main__":
35+
sol = Solution()
36+
print(sol.calculate(raw_input('Enter the expression: ')))

0 commit comments

Comments
 (0)
0