Python學習之輸入字符串計算其值


習題:輸入字符串計算其值:strr='1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))‘

習題之總結:

1.str是python內置函數,字符串命不能為命名str

2.字符串len和列表len長度不同

3.使用遞歸函數返回值

遺留問題:

1.字符串中內置多出空格導致正則表達式失效('1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) 此處有空格 )‘)。

2.字符串拆分時使用float類型計算和int 類型計算值相差比較大。

3.使用float類型計算出的值使用通用正則表達式失效。

4.計算出的結果和使用Eval()有差異,有bug?

eval計算結果:-294689
代碼計算結果:-294687

 

附上代碼,歡迎指正,謝謝!

 1 import os
 2 import re
 3 import time
 4 
 5 content = '1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
 6 # eval() get value
 7 print eval(content)
 8 # for get sub string values
 9 def countmd(str2,restr):
10     rs = re.split(restr, str2)
11     l1=rs[0:3]
12     l2 = rs[3:]
13     if l1[1].strip(' ') == "+":
14         rett = int(l1[0]) + int(l1[2])
15     elif l1[1].strip(' ') == "--":
16         rett = int(l1[0]) + int(l1[2])
17     elif l1[1].strip(' ') == "-":
18         rett = int(l1[0]) - int(l1[2])
19     elif l1[1].strip(' ') == "*":
20         rett = int(l1[0]) * int(l1[2])
21     elif l1[1].strip(' ') == "/":
22         rett = int(l1[0]) / int(l1[2])
23     l2.insert(0,str(rett))
24     if len(l2)>2:
25         str3="".join(l2)
26         return countmd(str3,restr)
27     else:
28         return rett
29 
30 # function for get  inner() values
31 def gh(strq):
32     strq=strq.strip(')').strip('(')
33     # re for add and mine
34     rejj='([\+\-\(\)]+)'
35     # re for multiply and divide
36     resc='([\/\*]+)'
37     rs2=[]
38     rs = re.split(rejj, strq)
39     for index, i in enumerate(rs):
40         if i.find('+')>0 or i.find('-')>0 or i.find('*')>0 or i.find('/')>0:
41             rs2.append(str(countmd(i.strip(')').strip('('),resc)))
42         else:
43             rs2.append(i)
44             pass
45     str4="".join(rs2)
46     rs2=filter(lambda x:x,rs2)
47     # print rs2
48     str4=str4.strip('(').strip(')')
49     if len(rs2)>2:
50         str4=countmd(str4,rejj)
51         return str4
52     else:
53         return str4
54 
55 
56 def mainc(ss):
57     # re for get inner ()
58     rw= re.split("(\([0-9\+\-\*\/]+\))",ss)
59     for index, i in enumerate(rw) :
60         if i.startswith('(') and i.endswith(')'):
61             rw[index]=str(gh(i)).strip('')
62     rw="".join(rw)
63     if rw.find('(')>0 :
64         rw=str(mainc(rw))
65     if rw.find('+')>0 or rw.find('-')>0 or rw.find('*')>0 or rw.find('/')>0:
66         return gh(rw)
67     else:
68         return rw
69 print mainc(content)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM