Created
January 17, 2010 12:59
-
-
Save hltbra/279362 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
>>> calcular('1') | |
1 | |
>>> calcular('(+ 1 2)') | |
3 | |
>>> calcular('(+ (- 1 2) 3)') | |
2 | |
>>> calcular('(- 0 (+ (+ 1 2) 3))') | |
-6 | |
''' | |
from pyparsing import Word, White, nums, Literal, OneOrMore, Group, Forward | |
numero = Word(nums) | |
abre_parenteses = Literal('(').suppress() | |
fecha_parenteses = Literal(')').suppress() | |
espacos = OneOrMore(White()).suppress() | |
mais = Literal('+') | |
menos = Literal('-') | |
expr = Forward() | |
atomo = numero | expr | |
expr << Group(numero | | |
(abre_parenteses + | |
(mais|menos) + espacos + atomo + espacos + atomo + | |
fecha_parenteses)) | |
OPERACOES = { | |
'+': lambda x, y: x + y, | |
'-': lambda x, y: x - y, | |
} | |
def avaliar(e): | |
if len(e) == 1: | |
return int(e[0]) | |
operacao = OPERACOES[e[0]] | |
return operacao(avaliar(e[1]), avaliar(e[2])) | |
def calcular(e): | |
expr_parseada = expr.parseString(e, True)[0] | |
return avaliar(expr_parseada) | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment