1.首先表示式的空格。
2.迴圈計算最內層帶括號的表示式(提取運算子出現的順序,然後計算)
3.計算最外層的表示式輸出。
剛接觸python,**不夠嚴謹,僅實現功能。不知道如何在函式中使用運算子變數做運算(使用的時候是字串形式),希望知道的朋友告訴我,互相學習一下。
importview codere,math
defqcysf(s):
while re.findall('
\+\-|\+\+|\-\-|\-\+
',s):
s = s.replace('
+-','-'
) s = s.replace('
++','+'
) s = s.replace('
--','+'
) s = s.replace('
-+','-'
)
return
sdef
yunsuan(a1):
temp1 = re.sub('
\d|\.|\+|-|
',''
,a1)
#print(temp1)
#print(a1)
for i in
temp1:
if i == "*"
: b = re.search('
(-?\d+\.?\d*\*-?\d+\.?\d*)
', a1).group()
#print(b)
temp2 = round(float(b.split('
*')[0]) * float(b.split('
*')[1]),10)
temp2 = '
+' +str(temp2)
a1 = a1.replace(b, temp2,1)
#print(a1)
else
: b = re.search('
(-?\d+\.?\d*/-?\d+\.?\d*)
', a1).group()
#print(b)
temp2 = round(float(b.split('
/')[0]) / float(b.split('
/')[1]),10)
temp2 = '
+' +str(temp2)
a1 = a1.replace(b, temp2,1)
#print(a1)
a1 =qcysf(a1)
#print(a1)
a2 = a1.lstrip('-'
) te*** = re.sub('
\d|\.|
', ''
, a2)
for i in
te***:
if i == "+"
: b = re.search('
(-?\d+\.?\d*\+\d+\.?\d*)
', a1).group()
temp2 = round(float(b.split('
+')[0]) + float(b.split('
+')[1]),10)
a1 = a1.replace(b, str(temp2),1)
#print(a1)
else
: b = re.search('
(\d+\.?\d*\-\d+\.?\d*)
', a1).group()
temp2 = round(float(b.split('
-')[0]) - float(b.split('
-')[1]),10)
a1 = a1.replace(b, str(temp2),1)
#print(a1)
return
a1if
__name__ == "
__main__":
a = input('
請輸入你要計算的內容:')
a = a.replace('
',''
)
#print(a)
if re.findall('
[a-za-z]]
',a):
print('
你輸入的內容不合法')
else
:
while re.search("
\([^()]+\)
", a):
b = re.search("
\([^()]+\)
", a).group()
#b = qcysf(b)
#print(a)
#print(b)
b1 = re.sub('
\(|\)
',''
,b)
#print(a)
temp =yunsuan(b1)
a =a.replace(b, str(temp))
#print('這是倒數第二個',a)
a =qcysf(a)
a =yunsuan(a)
print(a)
請輸入你要計算的內容:1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
2776672.6951997215
有效的括號python3
思路 本題括號排序特點和剛好與出入棧特點類似,因此考慮用出入棧來解決這個問題 判斷字串s是否為空,若為空返回f。判斷字串的length是否為奇數,若為奇數返回f。建立字典,將左括號 設定為value,一一對應。如果字元a是左括號,則入棧,否則通過字典判斷括號對應關係,若棧頂出棧括號與當前遍歷括號不對...
Python3簡單實現氣泡排序
話不多說,直接上 coding utf 8 class bubblesort object resultstr def init self,datas self.datas datas self.datas len len datas def sort self for i in range sel...
Python3簡單實現選擇排序
coding utf 8 class selectionsort object resultstr 初始化selectionsort def init self,datas self.datas datas self.datas len len datas def sort self for i i...