Guest User

Untitled

a guest
Mar 19th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. test_24_string = str(input("Enter your answer: "))
  2. test_24 = eval(test_24_string)
  3.  
  4. >>> import numexpr
  5. >>> numexpr.evaluate('2 + 4.1 * 3')
  6. array(14.299999999999999)
  7.  
  8. >>> numexpr.evaluate('17 / 3').item()
  9. 5.666666666666667
  10.  
  11. >>> b = 10
  12. >>> numexpr.evaluate('exp(17) / b').item()
  13. 2415495.27535753
  14.  
  15. >>> import ast
  16. >>> ast.literal_eval('1+2')
  17. 3
  18.  
  19. >>> ast.literal_eval('import os')
  20. SyntaxError: invalid syntax
  21.  
  22. >>> ast.literal_eval('exec(1+2)')
  23. ValueError: malformed node or string: <_ast.Call object at 0x0000023BDEADB400>
  24.  
  25. >>> ast.literal_eval('1.2 * 2.3')
  26. ValueError: malformed node or string: <_ast.BinOp object at 0x0000023BDEF24B70>
  27.  
  28. import operator
  29. import math
  30.  
  31. _add, _sub, _mul = operator.add, operator.sub, operator.mul
  32. _truediv, _pow, _sqrt = operator.truediv, operator.pow, math.sqrt
  33. _sin, _cos, _tan, _radians = math.sin, math.cos, math.tan, math.radians
  34. _asin, _acos, _atan = math.asin, math.acos, math.atan
  35. _degrees, _log, _log10 = math.degrees, math.log, math.log10
  36. _e, _pi = math.e, math.pi
  37. _ops = {'+': (2, _add), '-': (2, _sub), '*': (2, _mul), '/': (2, _truediv),
  38. '**': (2, _pow), 'sin': (1, _sin), 'cos': (1, _cos), 'tan': (1, _tan),
  39. 'asin': (1, _asin), 'acos': (1, _acos), 'atan': (1, _atan),
  40. 'sqrt': (1, _sqrt), 'rad': (1, _radians), 'deg': (1, _degrees),
  41. 'ln': (1, _log), 'log': (1, _log10)}
  42. _okeys = tuple(_ops.keys())
  43. _consts = {'e': _e, 'pi': _pi}
  44. _ckeys = tuple(_consts.keys())
  45.  
  46.  
  47. def postfix(expression):
  48. """
  49. Evaluate a postfix expression.
  50.  
  51. Arguments:
  52. expression: The expression to evaluate. Should be a string or a
  53. sequence of strings. In a string numbers and operators
  54. should be separated by whitespace
  55.  
  56. Returns:
  57. The result of the expression.
  58. """
  59. if isinstance(expression, str):
  60. expression = expression.split()
  61. stack = []
  62. for val in expression:
  63. if val in _okeys:
  64. n, op = _ops[val]
  65. if n > len(stack):
  66. raise ValueError('not enough data on the stack')
  67. args = stack[-n:]
  68. stack[-n:] = [op(*args)]
  69. elif val in _ckeys:
  70. stack.append(_consts[val])
  71. else:
  72. stack.append(float(val))
  73. return stack[-1]
  74.  
  75. In [2]: from postfix import postfix
  76.  
  77. In [3]: postfix('1 2 + 7 /')
  78. Out[3]: 0.42857142857142855
  79.  
  80. In [4]: 3/7
  81. Out[4]: 0.42857142857142855
Add Comment
Please, Sign In to add comment