算术表达式字符串求值
生活随笔
收集整理的這篇文章主要介紹了
算术表达式字符串求值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題: 計算字符串“10+12*13-30/20”的值
思路:
第一步:從左到右解析字符串,將數值與運算符放入數組
第二步:先計算乘除法,將求值放入隊列
第三步:依次出隊列,計算最終值
python代碼實現如下:
#!/usr/bin/python # -*- coding: utf-8 -*- import sys cal_string = '10+12*13-30/20' #分隔字符串 symbol = ['+', '-', '*', '/'] one_word = '' data = [] for c in cal_string:if c not in symbol:one_word += celse:data.append(int(one_word))data.append(c)one_word = '' data.append(one_word) print data#計算乘除,將運算完的值入隊列 hign_symbol = ['*', '/'] queue = [] cur_symbol = '' for one in data:if cur_symbol == '':if one in hign_symbol:cur_symbol = one else:queue.append(one)else:last_one = queue.pop()if cur_symbol == '*':new_one = float(last_one) * float(one) queue.append(new_one)else:new_one = float(last_one) / float(one)queue.append(new_one)cur_symbol = '' print queue#將隊列數據出隊列,計算最后值 result = 0 cur_symbol = '' for one in queue:if one != '+' and one != '-':if cur_symbol == '':result = oneelse:if cur_symbol == '+':result = result + oneelse:result = result - oneelse:cur_symbol = one print result 輸出結果: [10, '+', 12, '*', 13, '-', 30, '/', '20'] [10, '+', 156.0, '-', 1.5] 164.5總結
以上是生活随笔為你收集整理的算术表达式字符串求值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: curl命令使用总结
- 下一篇: 各互联网公司面试题整理