Skip to content

Instantly share code, notes, and snippets.

@Abdur-rahmaanJ
Created March 21, 2023 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Abdur-rahmaanJ/fa9308454df0450d76396468d85f9925 to your computer and use it in GitHub Desktop.
Save Abdur-rahmaanJ/fa9308454df0450d76396468d85f9925 to your computer and use it in GitHub Desktop.
postfix = ['111', '2', '+', '33', '2', '**', '+', '1', '1', '*', '-']
def is_number(num):
# quick way
return num[0] in '0123456789'
def eval_postfix(postfix):
stack = []
for element in postfix:
if is_number(element):
stack.append(element)
else:
v1 = int(stack.pop())
v2 = int(stack.pop())
if element == '**':
v = v2 ** v1
stack.append(v)
elif element == '*':
v = v2 * v1
stack.append(v)
if element == '/':
v = v2 // v1
stack.append(v)
if element == '+':
v = v2 + v1
stack.append(v)
if element == '-':
v = v2 - v1
stack.append(v)
return stack[0]
print(eval_postfix(postfix))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment