def push(stackArr,element):
stackArr.append(element)
def pop(stackArr):
return stackArr.pop()
def Operand(s):
if(not(Operator(s)) and (s != "(") and (s != ")")):
return 1
return 0
def Operator(s):
if(s == "+" or s == "-" or s == "*" or s == "/" or s == "%" or s == "^"):
return 1
return 0
def top(stackArr):
return(stackArr[len(stackArr)-1])
def isEmpty(stackArr):
if(len(stackArr) == 0):
return 1
return 0
def precedence(s):
if(s == "^"):
return 5
elif((s == "*") or (s == "/") or (s == "%")):
return 4
elif((s == "+") or (s == "-")):
return 3
elif(s == "("):
return 2
else:
return 1
def infix(infixStr,postfixStr = [],retType = 0):
postfixStr = []
stackArr = []
postfixPtr = 0
tempStr = infixStr
infixStr = []
infixStr = strToTokens(tempStr)
for i in infixStr:
if(Operand(i)):
postfixStr.append(i)
postfixPtr = postfixPtr+1
if(Operator(i)):
if(i != "^"):
while((not(isEmpty(stackArr))) and (precedence(i) <= precedence(top(stackArr)))):
postfixStr.append(top(stackArr))
pop(stackArr)
postfixPtr = postfixPtr+1
else:
while((not(isEmpty(stackArr))) and (precedence(i) < precedence(top(stackArr)))):
postfixStr.append(top(stackArr))
pop(stackArr)
postfixPtr = postfixPtr+1
push(stackArr,i)
if(i == "("):
push(stackArr,i)
if(i == ")"):
while(top(stackArr) != "("):
postfixStr.append(pop(stackArr))
postfixPtr = postfixPtr+1
pop(stackArr)
while(not(isEmpty(stackArr))):
if(top(stackArr) == "("):
pop(stackArr)
else:
postfixStr.append(pop(stackArr))
returnVal = ''
for i in postfixStr:
returnVal += i
if(retType == 0):
return(returnVal)
else:
return(postfixStr)
def postfix(postfixStr):
stackArr = []
tempStr = postfixStr
postfixStr = []
postfixStr = tempStr
for i in postfixStr:
if(Operand(i)):
push(stackArr,i)
else:
temp = top(stackArr)
pop(stackArr)
pop(stackArr)
push(stackArr,pushVal)
return(top(stackArr))
def strToTokens(str):
strArr = []
strArr = str
tempStr = ''
tokens = []
tokens_index = 0
count = 0
for i in strArr:
count = count+1
if(Operand(i)):
tempStr += i
if(Operator(i) or i == ")" or i == "("):
if(tempStr != ""):
tokens.append(tempStr)
tokens_index = tokens_index+1
tempStr = ''
tokens.append(i)
tokens_index = tokens_index+1
if(count == len(strArr)):
if(tempStr != ''):
tokens.append(tempStr)
return(tokens)
def menu():
def back():
option1 = raw_input('Mau Coba Lagi [Y/T]?').upper()
if option1 not in ('Y','T'):
back()
if(option1 == 'Y'):
menu()
if(option1 == 'T'):
exit
print '\n Menu yang dapat anda pilih'
print '\n(1) Ubah Infix Menjadi Postfix'
print '(2) Keluar'
option2 = raw_input("Masukkan Pilihan (1/2): ")
if option2 in ('1','2'):
if(option2 == '1'):
ifx = raw_input('\nMasukkan Notasi Infix : ')
print 'Notasi Postfix : ', infix(ifx)
if(option2 == '2'):
exit
if(option2 != '2'):
back()
else:
menu()
menu()
Program Konversi Infix Menjadi Postfix Pada Python
Subscribe to:
Post Comments (Atom)
0 komentar:
Post a Comment