🧮 2.6: Aritmetik İfadeler ve Stack

Polish Notation ve Dijkstra'nın İki-Stack Algoritması

1️⃣ Dijkstra'nın İki-Stack Algoritması

İfade: ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )

Bu algoritma, matematiksel ifadeleri iki stack kullanarak değerlendirir:

📊 Operand Stack

⚙️ Operator Stack

Başlamak için ilerleyin...

2️⃣ Kod İle Hesaplama

Aynı algoritmayı Python ile uygulayalım:

🐍 Python - İki Stack Algoritması
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)}")