|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# @Author: lock |
| 3 | +# @Date: 2017-06-26 15:51:28 |
| 4 | +# @Last Modified by: lock |
| 5 | +# @Last Modified time: 2017-06-26 15:55:53 |
| 6 | +def calc(s): |
| 7 | + if type(s) != list:s = s.split(' ') |
| 8 | + operaList = ['+', '-', '*', '/']; |
| 9 | + for key, item in enumerate(s): |
| 10 | + if item in operaList: |
| 11 | + val = eval(s[key - 2] + item + s[key - 1]) |
| 12 | + s.insert(key - 2, str(val)) |
| 13 | + for x in ['1','2','3']:del s[key - 1] |
| 14 | + calc(s) |
| 15 | + return sum(map(eval, s)) |
| 16 | +def translate(calcStr): |
| 17 | + element, calcList,s,stackStr,i = '', [],[],[],0 |
| 18 | + for key,item in enumerate(calcStr): |
| 19 | + if item.isdigit(): |
| 20 | + element = element + item |
| 21 | + if key == len(calcStr)-1:calcList.append(element) |
| 22 | + else: |
| 23 | + if element != '': |
| 24 | + calcList.append(element) |
| 25 | + element = '' |
| 26 | + if item in ['+', '-', '*', '/', '(', ')']: |
| 27 | + calcList.append(item) |
| 28 | + calcList.insert(0,'(') |
| 29 | + calcList.append(')') |
| 30 | + calcList.append('#') |
| 31 | + while calcList[i] != "#": |
| 32 | + if (calcList[i].isdigit()): |
| 33 | + stackStr.append(calcList[i]) |
| 34 | + elif calcList[i] == '(': |
| 35 | + s.append(calcList[i]) |
| 36 | + elif calcList[i] == ')': |
| 37 | + while s[-1] != '(': |
| 38 | + stackStr.append(s.pop()) |
| 39 | + s.pop() |
| 40 | + elif calcList[i] in ['+', '-']: |
| 41 | + while s[-1] != '(': |
| 42 | + stackStr.append(s.pop()) |
| 43 | + s.append(calcList[i]) |
| 44 | + elif calcList[i] in ['*', '/']: |
| 45 | + while s[-1] in ['*', '/']: |
| 46 | + stackStr.append(s.pop()) |
| 47 | + s.append(calcList[i]) |
| 48 | + i = i + 1 |
| 49 | + return stackStr |
| 50 | +if __name__ == '__main__': |
| 51 | + s = '11111111111111*9999999999999+(99-(12/4)+10)' |
| 52 | + print translate(s) |
| 53 | + print str(calc(translate('11111111111111*9999999999999+(99-(12/4)+10)'))) == str(11111111111111*9999999999999+(99-(12/4)+10)),str(calc(translate(s))) , str(11111111111111*9999999999999+(99-(12/4)+10)) |
| 54 | + print str(calc(translate('12+1+12+33*9+4'))) == str(12+1+12+33*9+4),str(calc(translate('12+1+12+33*9+4'))) , str(12+1+12+33*9+4) |
| 55 | + |
| 56 | + |
| 57 | + |
0 commit comments