2009-11-15 57 views
1

python初學者,但現在編程了大約5年。我懷疑我有很多東西要學習面向對象的方式,但我知道基礎知識。我計劃編寫一個計算器,顯示它對於我從中獲得的挑戰和知識是有用的。我剛開始,這就是我所擁有的,對我來說它看起來真的很醜。你會如何做到這一點?如何讓此Python代碼更易於使用和可讀?

P.S.這只是一個簡單的腳本,可以從括號內採取問題,添加它,顯示工作,然後評估完整問題。

import re 

def EvalParenths(problem): 
    contents = "" 
    if re.match("\(", problem): 
     contents = re.match("(\(.*\))", problem) 
     parenthsAnswer = contents.group(0) 
     problem = problem.replace(parenthsAnswer, '') 
     print " \ \n " + str(eval(parenthsAnswer)) + problem 
     problem = problem.replace(parenthsAnswer, '') 
     answer = eval(parenthsAnswer+problem) 
     print " \ \n " + str(answer) 
    else: 
     print "Didn't Find Parenthesis" 

def ProblemHasParenths(problem): 
    return re.match("\(", problem) 

""""" 
Example Problem: (12/4)*2 

""""" 

problem = raw_input() 

if ProblemHasParenths: 
    EvalParenths(problem) 
+2

這對我來說是非常易讀的,我對Python一點都不瞭解。 – Konamiman

+0

謝謝:) 我有時覺得自己做錯了什麼,因爲我一直都是自己編碼的,只是不覺得自己對OOP等知之甚少。 – Codygman

回答

2

如果你想做一個簡單的計算器,你可以嘗試實施Shunting-yard algorithm

但是,如果你想要去的正則表達式的方法,我還是會做一點點不同:

import re 

#In python functions/methods usually are lowercase 
#and words are seperated by _ while classes use CamelCasing 
def eval_step_by_step(expression): 
    """Evaluates math expression. Doesn't do any error checking. 
     expression (string) - math expression""" 

    print expression 
    #For pretty formating. 
    expr_len = len(expression) 
    #While there's parentheses in the expression. 
    while True: 
     #re.match checks for a match only at the beginning of the string, 
     #while re.search checks for a match anywhere in the string. 

     #Matches all numbers, +, -, *,/and whitespace within parentheses 
     #lazily (innermost first). 
     contents = re.search("\(([0-9|\*|/|\+|\-|\s]*?)\)", expression) 
     #If we didn't find anything, print result and break out of loop. 
     if not contents: 
      #string.format() is the Python 3 way of formating strings 
      #(Also works in Python 2.6). 

      #Print eval(expression) aligned right in a "field" with width 
      #of expr_len characters. 
      print "{0:{1}}".format(eval(expression), expr_len) 
      break 

     #group(0) [match] is everything matching our search, 
     #group(1) [parentheses_text] is just epression withing parentheses. 
     match, parentheses_text = contents.group(0), contents.group(1) 
     expression = expression.replace(match, str(eval(parentheses_text))) 
     #Aligns text to the right. Have to use ">" here 
     #because expression is not a number. 
     print "{0:>{1}}".format(expression, expr_len) 

#For example try: (4+3+(32-1)*3)*3 
problem = raw_input("Input math problem: ") 

eval_step_by_step(problem) 

它不工作完全一樣的功能,但你可以很容易地實現修改到您的函數來匹配我的。正如你所看到的,我還添加了很多評論來解釋一些東西。

+0

感謝您的算法推薦。沒有急於重寫,我即將睡覺無論如何:) 我正在閱讀調車場阿爾戈現在! – Codygman

+0

順便說一句,我想做一個計算器,顯示步驟的原因是我相信它會幫助我進入人工智能類型編程 – Codygman

+0

我已經更新了一些代碼,抱歉延遲了一些事情出現了。 –

5

一些問題:

contents = re.match("(\(.*\))", problem) 

當它給輸入(1+2)/(3+4),它會試圖評估1+2)/(3+4

它也不會一直嵌入到嵌套圓括號中,因此您需要使用遞歸。

我想你應該再次嘗試一下,然後再「查看答案」。

+0

當我早上起牀時會這樣做! 感謝您的建議 – Codygman

0

爲什麼不只匹配雙括號和匹配的括號?單打(的第一場比賽並不是必要的,因爲如果雙打比賽失敗,這意味着沒有任何表達方式可供您評估。

import re 

def eval_parentheses(problem): 
    contents = re.match("(\(.*\))", problem) 
    if contents: 
    ... 
    else: 
     print "Couldn't find parentheses!" 

此外,括號選擇算法可以改善一點對於嵌套的括號等

2

我大概用

problem.startswith("(") 

在更換的

re.match("\(", problem) 

出現

contents = re.match("(\(.*\))", problem) 
parenthsAnswer = contents.group(0) 

你不檢查,看看是否匹配的內容或不那麼如果你通過它,當你試圖評估contents.group(0)

不要你會得到一個異常輸入「(1」每一次使用eval在一個真正的程序!

您可以使用pyparsing來製作一個完整的解析器,但我認爲這是每個人都應該嘗試自己作爲練習至少一次的東西!