99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁(yè)精彩閱讀Python實(shí)現(xiàn)簡(jiǎn)單的四則運(yùn)算計(jì)算器
Python實(shí)現(xiàn)簡(jiǎn)單的四則運(yùn)算計(jì)算器
2017-08-16
收藏

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

相信大家在學(xué)習(xí)數(shù)據(jù)結(jié)構(gòu)時(shí),就學(xué)習(xí)了簡(jiǎn)單四則運(yùn)算表達(dá)式求解的一個(gè)算法,可惜一直沒有自己動(dòng)手實(shí)現(xiàn)過(guò)這個(gè)算法。最近重拾數(shù)據(jù)結(jié)構(gòu)與算法,恰巧又正在用Python比較頻繁,所幸就用它來(lái)實(shí)現(xiàn)這個(gè)算法,雖然網(wǎng)上有很多代碼,不過(guò)作為一個(gè)學(xué)習(xí)者,還是應(yīng)當(dāng)親自動(dòng)手實(shí)現(xiàn)。


一、算法

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)單示例如下:



測(cè)試案例

為了對(duì)這個(gè)計(jì)算器進(jìn)行有效地檢驗(yàn),設(shè)計(jì)了幾組測(cè)試案例,測(cè)試結(jié)果如下:

Test No.1: (1.11)=1.110000
Test No.2:1.11+2.22-3.33*4.44/5.55=0.666000
Test No.3:1.11+(2.22-3.33)*4.44/5.55=0.222000
Test No.4:1.11+(2.22-3.33)*(4.44+5.55)/6.66=-0.555000
Test No.5:1.11*((2.22-3.33)*(4.44+5.55))/(6.66+7.77)=-0.852992
Test No.6: (1.11+2.22)*(3.33+4.44)/5.55*6.66=31.048920
Test No.7: (1.11-2.22)/(3.33+4.44)/5.55*(6.66+7.77)/(8.88)=-0.041828
Test No.8: Error: (1.11+2.22)*(3.33+4.44: missing")", please check your expression
Test No.9: Error: (1.11+2.22)*3.33/0+(34-45): divisor cannot be zero
Test No.10: Error:12+89^7: invalid character: ^

實(shí)現(xiàn)代碼

棧的實(shí)現(xiàn)

棧實(shí)際上就是一個(gè)被限制操作的表,所有的操作只能在棧的頂端(入棧、出棧等),以下是使用Python代碼實(shí)現(xiàn)的簡(jiǎn)單的棧:

classStack(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
    """
    returnlen(self.__container)==0
  defpush(self, element):
    """
    Add a new element to the stack
    :param element: the element you want to add
    :return: None
    """
    self.__container.append(element)
  deftop(self):
    """
    Get the top element of the stack
    :return: top element
    """
    ifself.__is_empty():
      returnNone
    returnself.__container[-1]
  defpop(self):
    """
    Remove the top element of the stack
    :return: None or the top element of the stack
    """
    returnNoneifself.__is_empty()elseself.__container.pop()
  defclear(self):
    """
    We'll make an empty stack
    :return: self
    """
    self.__container.clear()
    returnself

計(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)清晰,還是分開來(lái)實(shí)現(xiàn)比較好,每個(gè)函數(shù)盡可能最好一件事情才是比較實(shí)在的。

在該計(jì)算器類中,有很多種極端的情況沒有被考慮進(jìn)去,因?yàn)槟菢拥脑捳麄€(gè)實(shí)現(xiàn)的代碼會(huì)更多。不過(guò),可以在后期為整個(gè)類繼續(xù)擴(kuò)展,添加新的功能也是可以的。目前實(shí)現(xiàn)的就是主要框架,包括基本的錯(cuò)誤檢測(cè)和運(yùn)算,重點(diǎn)時(shí)學(xué)習(xí)運(yùn)用棧這個(gè)看似簡(jiǎn)單卻強(qiáng)大的數(shù)據(jù)結(jié)構(gòu)解決問(wèn)題。

classCalculator(object):
  """
  A simple calculator, just for fun
  """
  def__init__(self):
    self.__exp=''
  def__validate(self):
    """
    We have to make sure the expression is legal.
    1. We only accept the `()` to specify the priority of a sub-expression. Notes: `[ {` and `] }` will be
    replaced by `(` and `)` respectively.
    2. Valid characters should be `+`, `-`, `*`, `/`, `(`, `)` and numbers(int, float)
    - Invalid expression examples, but we can only handle the 4th case. The implementation will
    be much more sophisticated if we want to handle all the possible cases.:
      1. `a+b-+c`
      2. `a+b+-`
      3. `a+(b+c`
      4. `a+(+b-)`
      5. etc
    :return: True or False
    """
    ifnotisinstance(self.__exp,str):
      print('Error: {}: expression should be a string'.format(self.__exp))
      returnFalse
    # Save the non-space expression
    val_exp=''
    s=Stack()
    forxinself.__exp:
      # We should ignore the space characters
      ifx==' ':
        continue
      ifself.__is_bracket(x)orself.__is_digit(x)orself.__is_operators(x) \
          orx=='.':
        ifx=='(':
          s.push(x)
        elifx==')':
          s.pop()
        val_exp+=x
      else:
        print('Error: {}: invalid character: {}'.format(self.__exp, x))
        returnFalse
    ifs.top():
      print('Error: {}: missing ")", please check your expression'.format(self.__exp))
      returnFalse
    self.__exp=val_exp
    returnTrue
  def__convert2postfix_exp(self):
    """
    Convert the infix expression to a postfix expression
    :return: the converted expression
    """
    # highest priority: ()
    # middle: * /
    # lowest: + -
    converted_exp=''
    stk=Stack()
    forxinself.__exp:
      ifself.__is_digit(x)orx=='.':
        converted_exp+=x
      elifself.__is_operators(x):
        converted_exp+=' '
        tp=stk.top()
        iftp:
          iftp=='(':
            stk.push(x)
            continue
          x_pri=self.__get_priority(x)
          tp_pri=self.__get_priority(tp)
          ifx_pri > tp_pri:
            stk.push(x)
          elifx_pri==tp_pri:
            converted_exp+=stk.pop()+' '
            stk.push(x)
          else:
            whilestk.top():
              ifself.__get_priority(stk.top()) !=x_pri:
                converted_exp+=stk.pop()+' '
              else:
                break
            stk.push(x)
        else:
          stk.push(x)
      elifself.__is_bracket(x):
        converted_exp+=' '
        ifx=='(':
          stk.push(x)
        else:
          whilestk.top()andstk.top() !='(':
            converted_exp+=stk.pop()+' '
          stk.pop()
    # pop all the operators
    whilestk.top():
      converted_exp+=' '+stk.pop()+' '
    returnconverted_exp
  def__get_result(self, operand_2, operand_1, operator):
    ifoperator=='+':
      returnoperand_1+operand_2
    elifoperator=='-':
      returnoperand_1-operand_2
    elifoperator=='*':
      returnoperand_1*operand_2
    elifoperator=='/':
      ifoperand_2 !=0:
        returnoperand_1/operand_2
      else:
        print('Error: {}: divisor cannot be zero'.format(self.__exp))
        returnNone
  def__calc_postfix_exp(self, exp):
    """
    Get the result from a converted postfix expression
    e.g. 6 5 2 3 + 8 * + 3 + *
    :return: result
    """
    assertisinstance(exp,str)
    stk=Stack()
    exp_split=exp.strip().split()
    forxinexp_split:
      ifself.__is_operators(x):
        # pop two top numbers in the stack
        r=self.__get_result(stk.pop(), stk.pop(), x)
        ifrisNone:
          returnNone
        else:
          stk.push(r)
      else:
        # push the converted number to the stack
        stk.push(float(x))
    returnstk.pop()
  def__calc(self):
    """
    Try to get the result of the expression
    :return: None or result
    """
    # Validate
    ifself.__validate():
      # Convert, then run the algorithm to get the result
      returnself.__calc_postfix_exp(self.__convert2postfix_exp())
    else:
      returnNone
  defget_result(self, expression):
    """
    Get the result of an expression
    Suppose we have got a valid expression
    :return: None or result
    """
    self.__exp=expression.strip()
    returnself.__calc()
  """
  Utilities
  """
  @staticmethod
  def__is_operators(x):
    returnxin['+','-','*','/']
  @staticmethod
  def__is_bracket(x):
    returnxin['(',')']
  @staticmethod
  def__is_digit(x):
    returnx.isdigit()
  @staticmethod
  def__get_priority(op):
    ifopin['+','-']:
      return0
    elifopin['*','/']:
      return1

總結(jié)

以上就是利用Python實(shí)現(xiàn)簡(jiǎn)單四則運(yùn)算計(jì)算器的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能有所幫助.



數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }