如何使这个Python代码更易于使用和可读?

时间:2009-11-15 08:43:11

标签: python oop usability readability

python中的初学者,但现在已经编程了大约5年。我怀疑我有很多东西要学习以面向对象的方式做事,但我知道基础知识。我计划编写一个计算器,显示它可以从中获得挑战和知识。我刚刚开始,这就是我所拥有的,它对我来说真的很难看。你会如何区别地做到这一点?

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)

4 个答案:

答案 0 :(得分:5)

一些问题:

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

当输入(1+2)/(3+4)时,它会尝试评估1+2)/(3+4

它也不会一直进入嵌套括号,为此你需要使用递归。

我认为你应该在“看看答案”之前再做一次尝试。

答案 1 :(得分: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)

它与您的函数完全不同,但您可以轻松地对函数进行修改以匹配我的函数。如你所见,我还添加了很多评论来解释一些内容。

答案 2 :(得分:2)

我可能会替换

的出现次数
re.match( "\(", problem)

problem.startswith("(")

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

你没有检查内容是否匹配所以如果你传递输入“(1”,当你试图评估contents.group(0)

时会得到一个例外

不要每次在真实程序中使用eval

你可以使用pyparsing制作一个完整的解析器,但我认为每个人都应该至少尝试一次自己的练习!

答案 3 :(得分:0)

为什么不匹配双括号和匹配括号?单个(的第一个匹配并不是必需的,因为如果双精度匹配失败,则表示没有表达式供您评估。

import re

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

此外,对于嵌套的parens等,可以对括号选择算法进行一些改进。