Skip to content

Instantly share code, notes, and snippets.

@jbochi
Created April 4, 2011 21:39
Show Gist options
  • Save jbochi/902503 to your computer and use it in GitHub Desktop.
Save jbochi/902503 to your computer and use it in GitHub Desktop.
Reverse Polish Notation
# avaliador de expressao em notacao polonesa reversa
funcoes = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"/": lambda a, b: a / b
}
def avalia(expressao):
pilha = []
for token in expressao.split(' '):
if token.isdigit():
pilha.append(int(token))
else:
operacao = funcoes[token]
op2, op1 = pilha.pop(), pilha.pop()
pilha.append(operacao(op1, op2))
return pilha.pop()
assert(avalia("3 3 +") == 6)
assert(avalia("2 5 *") == 10)
assert(avalia("5 20 15 - -") == 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment