国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Python實(shí)現(xiàn)簡(jiǎn)單的四則運(yùn)算計(jì)算器

2020-02-23 01:41:49
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

一、算法

     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í)在的。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 平武县| 延长县| 贵南县| 肥东县| 阜平县| 阜康市| 东兰县| 宁津县| 台中县| 唐河县| 恭城| 罗城| 简阳市| 确山县| 和平区| 乐平市| 海兴县| 凌源市| 邮箱| 秭归县| 德阳市| 洪洞县| 阳江市| 正宁县| 镇远县| 乌拉特前旗| 嘉定区| 烟台市| 枞阳县| 兴仁县| 灵川县| 左权县| 台北县| 弥渡县| 淅川县| 闵行区| 阳曲县| 镇赉县| 湖口县| 广宗县| 镇赉县|