私は大学のクラスの課題に取り組んでいます。私たちは大括弧で囲まれた数式の文字列を評価するスクリプトを書く必要があります。 )* 2)* 5) ')。また、教授が私たちに提供したこの課題には、スタックとキューを使用する必要があります。私のコードは動作するようになっていますが、適切な出力が得られません。私が間違っていることについての洞察は役に立ちます。ここでインジックスの表記法、スタックとキュー
は、Python 3で書かれた私のコードです:
import isfloat
import Queue
import Stack
def expr_eveluate(expr_string):
"""
:Pre: Given a mathematical expression, this function
evaluates it per pairs of brackets.
:Post: The expression must be evaluated per pairs of brackets
:param expr_string: A string of mathematical expressions
:return:
"""
# A queue for data to be processed.
waiting_line = Queue.create()
# A stack where processed operators go.
operator_stack = Stack.create()
# A stack where processed numbers go.
numerical_value = Stack.create()
# Put all the items in Queue
expr = expr_string.split()
for item in expr:
Queue.enqueue(waiting_line, item)
while not Queue.is_empty(waiting_line):
item = Queue.dequeue(waiting_line)
if item == '(':
pass
elif isfloat.isfloat(item):
Stack.push(numerical_value, item)
elif not isfloat.isfloat(item):
Stack.push(operator_stack, item)
else:
num1 = Stack.pop(numerical_value)
num2 = Stack.pop(numerical_value)
op = Stack.pop(operator_stack)
if op == '*':
val = num1 * num2
Stack.push(numerical_value, val)
if op == '/':
val = num1/num2
Stack.push(numerical_value, val)
if op == '+':
val = num1 + num2
Stack.push(numerical_value, val)
if op == '-':
val = num1 - num2
Stack.push(numerical_value, val)
else:
print("Syntax Error")
return None
return Stack.pop(numerical_value)
isfloatは私たちの教授が提供する別のモジュールです。文字を浮動小数点に変換しようとします。 –
私はあなたのタイトルで少し混乱しています。逆ポリッシュ表記法では、引数の後に演算子があります(たとえば '1 2 +')が、カッコで通常の表記法を尋ねています(例えば '(1 + 2)')。 – Blckknght
ああ申し訳ありませんが、私は表記自体に慣れていませんが、私の友人はそれがRPNかPostfix表記であると言いました。 –