一、算法
1、算法的主要思想就是將一個(gè)中綴表達(dá)式(Infix expression)轉(zhuǎn)換成便于處理的后綴表達(dá)式(Postfix expression),然后借助于棧這個(gè)簡(jiǎn)單的數(shù)據(jù)結(jié)構(gòu),計(jì)算出表達(dá)式的結(jié)果。
2、關(guān)于如何講普通的表達(dá)式轉(zhuǎn)換成后綴表達(dá)式,以及如何處理后綴表達(dá)式并計(jì)算出結(jié)果的具體算法描述不在此敘述了,書上有詳細(xì)的說(shuō)明。
二、簡(jiǎn)易計(jì)算器
使用說(shuō)明
使用該計(jì)算器類的簡(jiǎn)單示例如下:
# usagec = Calculator()print('result: {:f}'.formart(c.get_result('1.11+2.22-3.33*4.44/5.55')))# output:result: 0.666000
測(cè)試案例
為了對(duì)這個(gè)計(jì)算器進(jìn)行有效地檢驗(yàn),設(shè)計(jì)了幾組測(cè)試案例,測(cè)試結(jié)果如下:
Test No.1: (1.11) = 1.110000Test No.2: 1.11+2.22-3.33*4.44/5.55 = 0.666000Test No.3: 1.11+(2.22-3.33)*4.44/5.55 = 0.222000Test No.4: 1.11+(2.22-3.33)*(4.44+5.55)/6.66 = -0.555000Test No.5: 1.11*((2.22-3.33)*(4.44+5.55))/(6.66+7.77) = -0.852992Test No.6: (1.11+2.22)*(3.33+4.44)/5.55*6.66 = 31.048920Test No.7: (1.11-2.22)/(3.33+4.44)/5.55*(6.66+7.77)/(8.88) = -0.041828Test No.8: Error: (1.11+2.22)*(3.33+4.44: missing ")", please check your expressionTest No.9: Error: (1.11+2.22)*3.33/0+(34-45): divisor cannot be zeroTest No.10: Error: 12+89^7: invalid character: ^
實(shí)現(xiàn)代碼
棧的實(shí)現(xiàn)
棧實(shí)際上就是一個(gè)被限制操作的表,所有的操作只能在棧的頂端(入棧、出棧等),以下是使用Python代碼實(shí)現(xiàn)的簡(jiǎn)單的棧:
class Stack(object): """ The structure of a Stack. The user don't have to know the definition. """ def __init__(self): self.__container = list() def __is_empty(self): """ Test if the stack is empty or not :return: True or False """ return len(self.__container) == 0 def push(self, element): """ Add a new element to the stack :param element: the element you want to add :return: None """ self.__container.append(element) def top(self): """ Get the top element of the stack :return: top element """ if self.__is_empty(): return None return self.__container[-1] def pop(self): """ Remove the top element of the stack :return: None or the top element of the stack """ return None if self.__is_empty() else self.__container.pop() def clear(self): """ We'll make an empty stack :return: self """ self.__container.clear() return self
計(jì)算器類的實(shí)現(xiàn)
在計(jì)算器類中,我們將表達(dá)式的合法性驗(yàn)證單獨(dú)放在一個(gè)函數(shù)中完成,但是實(shí)際上如果需要,也可以直接放在中綴表達(dá)式轉(zhuǎn)后綴表達(dá)式的函數(shù)中實(shí)現(xiàn),這樣只需要一次遍歷表達(dá)式即可同時(shí)完成驗(yàn)證和轉(zhuǎn)換工作。但是為了保持結(jié)構(gòu)清晰,還是分開(kāi)來(lái)實(shí)現(xiàn)比較好,每個(gè)函數(shù)盡可能最好一件事情才是比較實(shí)在的。
新聞熱點(diǎn)
疑難解答
圖片精選