Skip to content

Instantly share code, notes, and snippets.

@alyssonbruno
Created July 25, 2012 15:17
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 alyssonbruno/3176731 to your computer and use it in GitHub Desktop.
Save alyssonbruno/3176731 to your computer and use it in GitHub Desktop.
Verificando expressão numérica
def eval_expr(text):
test_char = lambda c: c in '1234567890.,*/+-()'
for char in text:
if not test_char(char):
raise Exception('Invalid Char in String')
return long(eval(text,{},{}))
@perone
Copy link

perone commented Jul 25, 2012

    import string
    def eval_expr(expr):
        valid = set(string.digits + string.punctuation)
        for c in expr:
            if c not in valid:
                raise RuntimeError('Invalid expression')
        return long(eval(expr, {}, {}))

@alyssonbruno
Copy link
Author

O problema com o string.punctuation é que veem muito caracteres extras, com o ! e o ? que vai gerar uma outra exceção, o que às vezes não é ruim, mas não se encaixaria no meu problema.

@perone
Copy link

perone commented Jul 25, 2012

Entendi, mas você pode usar o string.digits e também remover a função lambda.

@santagada
Copy link

não testei, mas faria algo assim:

import re
def eval_expr(text):
    if not re.match('^[-0-9.,*/+()]*$'):
            raise ValueError('Invalid char in string')
    return eval(text, {}, {})

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