1

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

PS这只是一个简单的脚本,用于从括号内取出问题,将其相加,展示工作,然后评估完整的问题。

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

4 回答 4

5

一些问题:

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

当它给出 input(1+2)/(3+4)时,它会尝试评估1+2)/(3+4

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

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

于 2009-11-15T09:18:04.000 回答
2

如果你想做一个简单的计算器,你可以尝试实现Shutting-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)

它与您的功能不完全相同,但您可以轻松地对您的功能进行修改以匹配我的功能。正如你所看到的,我还添加了很多评论来解释一些东西。

于 2009-11-15T09:09:51.960 回答
2

我可能会替换出现的

re.match( "\(", problem)

problem.startswith("(")

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

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

不要每次都eval在实际程序中使用!

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

于 2009-11-15T09:19:20.970 回答
0

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

import re

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

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

于 2009-11-15T09:18:10.810 回答