【问题标题】:How Can I Make This Python Code More Usable And Readable?我怎样才能使这个 Python 代码更有用和可读?
【发布时间】:2009-11-15 08:43:10
【问题描述】:

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)

【问题讨论】:

  • 对我来说可读性很强,我对 Python 不太了解。
  • 谢谢 :) 我有时觉得我做的一切都是错的,因为我总是自己编写代码,只是觉得我对 OOP 等了解不够。

标签: python oop usability readability


【解决方案1】:

一些问题:

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

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

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

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

【讨论】:

  • 我早上起床时会做!感谢您的建议
【解决方案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)

它与您的函数的工作方式并不完全相同,但您可以轻松地对您的函数进行修改以匹配我的函数。如您所见,我还添加了很多 cmets 来解释一些东西。

【讨论】:

  • 感谢算法推荐。不急于重写,反正我要睡觉了 :) 我现在正在阅读调车场算法!
  • 顺便说一句,我想做一个显示步骤的计算器的原因是我相信它会帮助我进入人工智能类型的编程
  • 我已经更新了一些代码,抱歉耽搁了。
  • 哦,是的,您也可以使用递归(可能更 Pythonic)来编写它。
【解决方案3】:

我可能会替换出现的

re.match( "\(", problem)

problem.startswith("(")

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

您不会检查内容是否匹配,因此如果您将输入“(1”传递给它,您将在尝试评估 contents.group(0) 时遇到异常

不要在实际程序中使用eval

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

【讨论】:

    【解决方案4】:

    为什么不只匹配双括号和匹配的括号?单个 ( 的第一次匹配并不是真正必要的,因为如果双精度匹配失败,这意味着没有表达式可供您评估。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      相关资源
      最近更新 更多