Polish Notation ve Dijkstra'nın İki-Stack Algoritması
İfade: ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )
Bu algoritma, matematiksel ifadeleri iki stack kullanarak değerlendirir:
Aynı algoritmayı Python ile uygulayalım:
def evaluate_infix(expression):
values = [] # Sayılar
ops = [] # Operatörler
tokens = expression.replace('(', ' ( ').replace(')', ' ) ').split()
for token in tokens:
if token == '(':
pass # Atla
elif token in "+-*/":
ops.append(token)
elif token == ')':
# Kapanış gelince işlemi yap
op = ops.pop()
val2 = values.pop()
val1 = values.pop()
if op == '+': res = val1 + val2
elif op == '-': res = val1 - val2
elif op == '*': res = val1 * val2
elif op == '/': res = val1 / val2
values.append(res)
print(f"İşlem: {val1} {op} {val2} = {res}")
else:
values.append(float(token))
return values.pop()
expr = "( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )"
print(f"\\nSonuç: {evaluate_infix(expr)}")