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

簡単な計算機を作成したい場合は、Shunting-yard アルゴリズムの実装を試すことができます。

しかし、正規表現のアプローチを使用したい場合は、少し違った方法で行います:

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" を渡すと、contents.group(0) を評価しようとすると例外が発生します。

eval実際のプログラムで毎回使用しないでください。

pyparsingを使用して完全なパーサーを作成することもできますが、これは誰もが少なくとも 1 回は演習として自分で試してみるべき種類のものだと思います。

于 2009-11-15T09:19:20.970 に答える
0

二重括弧と一致する括弧だけを一致させてみませんか? (double の一致が失敗した場合、評価する式がないことを意味するため、single の最初の一致は実際には必要ありません。

import re

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

また、括弧の選択アルゴリズムは、ネストされた括弧などに対して少し改善される可能性があります。

于 2009-11-15T09:18:10.810 に答える