Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save saiftheboss7/65eacb8998d47a5912fcf818a5e5b363 to your computer and use it in GitHub Desktop.
Save saiftheboss7/65eacb8998d47a5912fcf818a5e5b363 to your computer and use it in GitHub Desktop.
Postfix Evaluation of an expression using Python 3
s = []
while True:
'''Taking Input until user clicks a blank enter'''
item=input("Enter your postfix expression character by character or press enter to exit ")
if (item==''):
break
s.append(item) #Adding items to stack one by one
print(s) #your entered expression
j=[]
for i in range(len(s)): #loop for checking each characer one by one
if(s[i].isdigit()==True): #if the character is a digit that will be stored in another array j
j.append(int(s[i]))
elif(s[i]=='*'):
#if * operator then first pop will pop the last element and second pop will do the last-1 element.
#now we need to swap as the left most between the two will be operand 1, and operand2 will be the right one.
x=j.pop()
y=j.pop()
res = y * x
j.append(res)
elif(s[i]=='+'):
x=j.pop()
y=j.pop()
res = y + x
j.append(res)
elif(s[i]=='-'):
#if * operator then first pop will pop the last element and second pop will do the last-1 element.
#now we need to swap as the left most between the two will be operand 1, and operand2 will be the right one.
#ex: if 6,4 is appended and we do operation withour swapping it'll be 4-6=-2
x=j.pop()
y=j.pop()
res = y - x
j.append(res)
elif(s[i]=='/'):
#ex: if we do not swap 6,3 will be resulted as 3/6.
x=j.pop()
y=j.pop()
res=y/x
j.append(res)
print('Your postfix expression result is',j[0])
Copy link

ghost commented Aug 8, 2018

Tq.its helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment