Selasa, 15 Mei 2018

Infix To Postfix + Evaluasi

Infix To Postfix pada Python

from __future__ import print_function

class Stack:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items==[]

    def push(self,items):
        self.items.append(items)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()  
    print (tokenList)
    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]) :
                postfixList.append(opStack.pop())
            opStack.push(token)
    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)

def postfixEval(postfixExpr):
    operandStack = Stack()
    tokenList = postfixExpr.split()
    for token in tokenList:
        if token in "0123456789":
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token,operand1,operand2)
            operandStack.push(result)
    return operandStack.pop()

def doMath(op, op1, op2):
    if op == "*":
        return op1 * op2
    elif op == "/":
        return op1 / op2
    elif op == "+":
        return op1 + op2
    else:
        return op1 - op2


# Infix To Postfix
data = input("Masukan Infix (Dalam bentuk String dan tambahan spasi): ")
postfix = infixToPostfix(data)
print (postfix)

# Postfix Evaluasi
data2 = input("Masukan Postfix (Dalam bentuk Angka dan tambahan spasi): ")
infix = postfixEval(data2)
print (infix)

Tidak ada komentar:

Posting Komentar

Sejarah, Kegiatan, dan Dokumnetasi Angkatan Teknik Informatika 2017 (INTEGER_17)

Sejarah, Kegiatan, dan Dokumentasi Angkatan Teknik Informatika 2017 (INTEGER_17) Assalamualaikum Wr. Wb. INTEGER Information Te...