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

2024-10-03 04:39:09 发布

您现在位置:Python中文网/ 问答频道 /正文

python初学者,但已经编程5年了。我想我有很多东西要学,以面向对象的方式做事情,但我知道基本的。我计划编程一个计算器,显示它的工作挑战和知识,我将从中获得。我刚开始,这就是我所拥有的,只是在我看来真的很难看。你会有什么不同的做法呢?在

附言:这只是一个简单的脚本,把问题从括号里拿出来,加起来,展示工作,然后评估整个问题。在

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)

Tags: answerreifdefmatch编程evalcontents
3条回答

一些问题:

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

当给定输入(1+2)/(3+4)时,它将尝试计算1+2)/(3+4。在

它也没有完全进入嵌套括号,为此,您需要使用递归。在

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

我可能会替换

re.match( "\(", problem)

^{pr2}$

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

你不检查内容是否匹配,所以如果你传递给它输入“(1”,当你试图计算时,你会得到一个异常目录.组(0)

不要在一个真正的程序中使用eval!在

您可以使用pyparsing来创建一个完整的解析器,但我认为这是每个人都应该自己尝试至少一次的事情!在

如果你想做一个简单的计算器,你可以尝试实现Shunting-yard algorithm。在

但如果您想使用regex方法,我还是会做一些不同的事情:

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)

实现你的功能和我的功能不太一样。如你所见,我还添加了很多注释来解释一些东西。在

相关问题 更多 >