これは標準的なインタビュー質問です。文字列の形式で与えられた数式を評価します。数式を文字列形式で評価する
に設けられ、'3+3-6*2'
答えは-6
式は4つだけの操作+,-,*,/
をサポートしている場合さて、スタックを使用してそれを行うための簡単な方法があるはずです。
私は中置記法を後置に変換し、それをスタックを使って解決することで解決しましたが、私はこれらの4つの操作だけをサポートする別のアプローチを探しています。これが私の解決策である、
def evaluate(self, s: str) -> int:
expr = [i for i in re.split(r'(\d+|\W+)', s) if i]
rpn = self.convertToPostfix(expr)
return self.evalPostfix(rpn)
def convertToPostfix(self, infix: list) -> list:
stack = collections.deque()
result = []
for item in infix:
if item.isdigit():
result.append(item)
else:
while len(stack) > 0 and self.has_higher_precedence(stack[-1], item):
result.append(stack[-1])
stack.pop()
stack.append(item)
while len(stack) > 0:
result.append(stack.pop())
return result
def has_higher_precedence(self, a: str, b: str) -> bool:
if a == '/' and b == '*' or b == '+' or b == '-':
return True
if a == '*' and b == '+' or '-':
return True
if a == '+' and b == '-':
return True
return False
def evalPostfix(self, p: list) -> int:
stack = collections.deque()
for item in p:
if item.isdigit():
stack.append(int(item))
elif item[1:].isdigit():
stack.append(int(item))
else:
curr = stack.pop()
prev = stack.pop()
if item == '+':
total = prev + curr
elif item == '-':
total = prev - curr
elif item == '*':
total = prev * curr
else:
total = prev/curr
stack.append(total)
return stack.pop()
はまた、私は、これは再帰的な字句パーサを設計することによって解決することができることを承知しているが、それはこの質問の範囲を超えています。スタックを使用して
だから私の質問は、Oでこれを行うための簡単な方法(n)の時間がある時のみ4事業者
[Shunting-yardアルゴリズム](https://en.wikipedia.org/wiki/Shunting-yard_algorithm)は、この問題を解決するための標準的な方法です。あなたの方程式にカッコはありませんので、単純化したい場合は、アルゴリズムのその部分を残しておくことができます。 –
@ JimMischel私のコードは基本的にシャントヤードアルゴリズムの実装だと思います。 –
括弧なしでスタックを必要としない場合でも、有限メモリで十分です。 –