Basic Calculator
2015-08-22 21:00
253 查看
题目:
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open
the plus
and empty spaces .
You may assume that the given expression is always valid.
Some examples:
Note: Do not use the
library function.
解题思路:
是关于中缀表达式的计算,需要用到栈。思路比较简单,用两个栈,一个存储操作数,一个存储操作符。根据每个操作符的优先次序赋予相应的权值。不断进行入栈操作,直到得出结果。代码如下:
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
def cal(num1,num2,op):
if op=='+':
return num1+num2
elif op=='-':
return num1-num2
def readNum(s,index):
res = 0
while s[index] in '0123456789':
res = 10*res+int(s[index])
index = index+1
return res,index
map = {'$':0, '(':1, ')':1, '+':2, '-':2}
operator, operand = ['$'], []
s = ''.join((s+'$').split())
index = 0
while len(operator)!=0:
i = s[index]
if i not in '()+-$':
num ,index= readNum(s,index)
operand.append(num)
else:
if i=='$' and operator[len(operator)-1]=='$':
return operand.pop()
elif i==')' and operator[len(operator)-1]=='(':
operator.pop()
index += 1
elif i=='(' or map[i]>map[operator[len(operator)-1]]:
operator.append(i)
index += 1
else:
num1,num2 = operand.pop(), operand.pop()
num = cal(num2,num1,operator.pop())
operand.append(num)
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open
(and closing parentheses
),
the plus
+or minus sign
-, non-negative integers
and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the
evalbuilt-in
library function.
解题思路:
是关于中缀表达式的计算,需要用到栈。思路比较简单,用两个栈,一个存储操作数,一个存储操作符。根据每个操作符的优先次序赋予相应的权值。不断进行入栈操作,直到得出结果。代码如下:
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
def cal(num1,num2,op):
if op=='+':
return num1+num2
elif op=='-':
return num1-num2
def readNum(s,index):
res = 0
while s[index] in '0123456789':
res = 10*res+int(s[index])
index = index+1
return res,index
map = {'$':0, '(':1, ')':1, '+':2, '-':2}
operator, operand = ['$'], []
s = ''.join((s+'$').split())
index = 0
while len(operator)!=0:
i = s[index]
if i not in '()+-$':
num ,index= readNum(s,index)
operand.append(num)
else:
if i=='$' and operator[len(operator)-1]=='$':
return operand.pop()
elif i==')' and operator[len(operator)-1]=='(':
operator.pop()
index += 1
elif i=='(' or map[i]>map[operator[len(operator)-1]]:
operator.append(i)
index += 1
else:
num1,num2 = operand.pop(), operand.pop()
num = cal(num2,num1,operator.pop())
operand.append(num)
相关文章推荐
- SGU 102(Coprimes)
- Linux crontab定时执行任务 命令格式与详细例子
- 大图处理
- Selenium的封装与重用
- js 正则表达式一看就懂
- Mybatis基础操作
- 里氏替换原则
- HDU_1754 I Hate It(线段树)
- Add Digits
- java中string与json互相转化
- 我多希望我学编程时,有人教我这些事!
- 5种类型的程序员
- java file 删除目录下无用的文件
- 快速排序
- 用户体验工程师的多重角色
- [ACdream]小Y上学记——要迟到了![最短路][spfa]
- Implementation of Serial Wire JTAG flash programming in ARM Cortex M3 Processors
- Android中定时
- Linux - bash : ifconfig command not found
- MVC处理程序类型