Advertisement
Guest User

Untitled

a guest
May 1st, 2021
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. import ast
  2.  
  3. def limited_eval(node):
  4. if isinstance(node, ast.Expression):
  5. return limited_eval(node.body)
  6. elif isinstance(node, ast.BinOp):
  7. ops = [
  8. (ast.Add, lambda a,b: a+b),
  9. (ast.Sub, lambda a,b: a-b),
  10. (ast.Mult, lambda a,b: a*b),
  11. (ast.Div, lambda a,b: a/b)
  12. ]
  13. for t, func in ops:
  14. if isinstance(node.op, t):
  15. return func(limited_eval(node.left), limited_eval(node.right))
  16. raise NotImplementedError(f"BinOp with operator {repr(node.op)}")
  17. elif isinstance(node, ast.Constant):
  18. return node.value
  19. else:
  20. raise NotImplementedError(str(type(node)))
  21.  
  22. s = "2+2*3+4/4"
  23. x = ast.parse(s, mode="eval")
  24. print(limited_eval(x)) #9.0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement