Selasa, 15 Mei 2018

Infix To Prefix + Evaluasi

Infix To Prefix pada Python

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 replace(data):
    for i in range(len(data)):
        if data[i]=='(':
            data[i]=')'
        elif data[i]==')':
            data[i]='('
    return data

def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr 
    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
    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

#Main Program
infix = input("Masukan : ")
a = infix.split()
Data = []
for i in range (len(a)):
    Data.append(a[i])
data2= Data[::-1]
hasil = replace(data2)
total1 = infixToPostfix(hasil)
total = total1[::-1]
print (total)

Preval = input("Masukan : ")
b = Preval.split()
Data2 = []
for i in range (len(b)):
    Data2.append(b[i])
Datum = Data2[::-1]
eval1 = postfixEval(Datum)
print (eval1)

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...