3

私はプログラミングにかなり慣れていません。これはpythonに関連しています。したがって、アイデアは、3/5 または最大で 3/5*2 (最大で 2 つの演算子、演算子は +、-、/、* のいずれかであることに注意してください) などの式を取り、それを解くことです。空白は、式内のどこにでも存在できます。

ユーザーが 3/5 などの式を入力すると、プログラムは式を解いて答えを表示する必要があります。私が試したことは以下です。ユーザーが入力した元の式(文字列)を適切に分割できたら、最初の部分だけを試みたことに注意してください。関数の作成は簡単な部分です。

expres= str(input("something:"))

ssplit= hit.partition("/")
onec= int((ssplit[0].lstrip()).rstrip())
twoc= (ssplit[1].lstrip()).rstrip()
threec= int((huns[2].lstrip()).rstrip())


print(onec,"...",twoc,"...",threec) #just a debug test print

上記のように、3/5 のような式を 3 、/、および 5 の 3 つの個別の文字列に分割できます。また、演算子/オペランドの前後のすべての空白を削除することもできます。ssplit[3] または ssplit[4] のコードを入力できず、定義されないため、3/5 のような式を入力できないため、4/5+6 のような式の分割に問題があります。基本的に、3/4-6 などの式を分割する方法を見つけるためにあなたの助けが必要でした。ssplit= hit.partition("/")入力された式を見て、+、-、および * でも機能するように、行 " " についても助けが必要です。ありとあらゆる助けをいただければ幸いです。また、上記のコードが厄介で非効率に見える場合は、批判してください。ありがとう!

eval は使用できないし、使用したくないことに注意してください。操作の順序が必要です。複雑なコマンドは使えません。シンプルに保つ必要があります。使用できるのは、文字列ライブラリ、文字列/整数/浮動小数点数などとif、andなどの間の変換です。ステートメント。関数も使えます。

4

3 に答える 3

10

外部ライブラリに依存するつもりがなければ、次のようにします。

def parse(x):
    operators = set('+-*/')
    op_out = []    #This holds the operators that are found in the string (left to right)
    num_out = []   #this holds the non-operators that are found in the string (left to right)
    buff = []
    for c in x:  #examine 1 character at a time
        if c in operators:  
            #found an operator.  Everything we've accumulated in `buff` is 
            #a single "number". Join it together and put it in `num_out`.
            num_out.append(''.join(buff))
            buff = []
            op_out.append(c)
        else:
            #not an operator.  Just accumulate this character in buff.
            buff.append(c)
    num_out.append(''.join(buff))
    return num_out,op_out

print parse('3/2*15')

それは最もエレガントではありませんが、合理的なデータ構造で断片を取得します(とにかく私に関する限り)

次に、実際に数値を解析して評価するコードを作成します。これにより、すべてが浮動小数点で実行されますが、変更するのは簡単です...

import operator
def my_eval(nums,ops):

    nums = list(nums)
    ops = list(ops)
    operator_order = ('*/','+-')  #precedence from left to right.  operators at same index have same precendece.
                                  #map operators to functions.
    op_dict = {'*':operator.mul,
               '/':operator.div,
               '+':operator.add,
               '-':operator.sub}
    Value = None
    for op in operator_order:                   #Loop over precedence levels
        while any(o in ops for o in op):        #Operator with this precedence level exists
            idx,oo = next((i,o) for i,o in enumerate(ops) if o in op) #Next operator with this precedence         
            ops.pop(idx)                        #remove this operator from the operator list
            values = map(float,nums[idx:idx+2]) #here I just assume float for everything
            value = op_dict[oo](*values)
            nums[idx:idx+2] = [value]           #clear out those indices

    return nums[0]

print my_eval(*parse('3/2*15'))
于 2012-10-24T19:15:04.820 に答える
2

これは実際には式を解析する方法ではありません。PLYやpyparsingなどのレクサーとパーサーを詳しく調べる必要あります。ただし、式を評価するだけの場合は、を使用できますeval(expr)。evalはフィードしたコードを実行するため、実際には安全ではないことに注意してください。

編集 pyparsingを使用するための例がここにあります、それはあなたが始めるはずです:

pyparsingの例

于 2012-10-24T19:04:44.923 に答える
2

shlexおよびStringIOPython モジュールを使用します。Python 2.3 以降の場合:

>>> from StringIO import StringIO
>>> import shlex
>>> input = StringIO('3/4+5')
>>> list(shlex.shlex(input))
['3', '/', '4', '+', '5']
于 2012-10-24T20:21:01.263 に答える