Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
perform_math.py
#python 3.4.3 #!/usr/bin/env python3 # perform_math.py # get some math functions and use them # after converting a string to a math expression # using abstract syntax tree module # # Since eval as a function is unsafe (arbitrary code/shellcode could be run) # we limit our expression in our syntax tree to the kinds of syntax we are # interested in. This prevents "other" kinds of expressions from being allowed. import ast import math # get math functions and constants like pi and e # avoid the generic object class methods that start with _ mathfuncs = {key: value for (key,value) in list(vars(math).items()) if key[0] != '_'} # add in the arithmetic builtin functions b_ins = {"abs": abs, "bin": bin, "complex": complex, "hex": hex, "min": min, "max": max, "pow": pow, "range":range, "round": round} mathfuncs.update( b_ins ) # creat your own def reciprocal(x): if isinstance(x, (int, float)): return 1/x elif isinstance(x, (complex)): import cmath return x.conjugate() else: raise TypeError(x) inverse = reciprocal # more than one name! def bin2hex(b): if isinstance(b, (str) ): return hex(int( b, base = 2)) elif isinstance(b, (int) ): return hex(int(b)) def hex2bin(h): if isinstance(h, (str) ): return bin(int( h, base = 16)) elif isinstance(h, (int) ): return bin(int(h)) # add them too mathfuncs.update( { "bin2hex" : bin2hex, "hex2bin" : hex2bin, "reciprocal": reciprocal, "inverse":inverse} ) # tuples are immutable whitelist = (ast.Module, ast.Expr, ast.Load, ast.Expression, ast.Add, ast.Sub, ast.UnaryOp, ast.Num, ast.BinOp, ast.Mult, ast.Div, ast.Pow, ast.BitOr, ast.BitAnd, ast.BitXor, ast.USub, ast.UAdd, ast.FloorDiv, ast.Mod, ast.LShift, ast.RShift, ast.Invert, ast.Call, ast.Name) # subclass wrapper that only evaluates math expressions on the whitelist class MathVisitor (ast.NodeVisitor): def __init__(self, wl ): assert isinstance(wl, (tuple)) self.whitelist = wl def visit(self, node): if not isinstance(node, self.whitelist): raise ValueError(node) return super().visit(node) # call ast.NodeVisitor.visit(node) # a function to do the evaulation def evaluate(expr, locals = {}): if any(elem in expr for elem in '\n#') : raise ValueError(expr) try: node = ast.parse(expr.strip(), mode='eval') MathVisitor(whitelist).visit(node) return eval(compile(node, "<string>", "eval"), {'__builtins__': None}, mathfuncs ) except Exception: raise ValueError(expr) # print out all the math functions we got print ( "All your mathfunc are belong to us:\n") s=[] for k,v in list(mathfuncs.items()): s.append(k) sorted(s) # tabular formatting sep = 10 for x in range(1, len(s)-4, 5): print(( s[x].ljust(sep), s[x+1].ljust(sep), s[x+2].ljust(sep), s[x+3].ljust(sep), s[x+4].ljust(sep) )) # do some work with this exp="(20.0**3.4) / (31.5 * 3.4)" e = evaluate(exp) print(( "\n%s = %10f\n" % (exp, e) )) exp = "- ( pow(5,6) / factorial((3*2)) )" e = evaluate(exp) print(( "\n%s = %10f\n" % (exp, e) )) exp = " reciprocal ( " + str(e) + " )" re = evaluate(exp) print(( "\ninverse of %s = %16f\n" % (exp, re) )) m = e * re print(( "\n%f * %f = %16f\n" % (e, re, m) )) r = round(e * re, 16) print(( "\nrounded to %d places = %16f\n" % (16, r) )) exp = "bin2hex(0b11011110101011011111101011001110)" h = evaluate(exp) print(("hex:\t %s\n" % (h) )) exp = "hex2bin(0xdeadface)" b = evaluate(exp) print(("bin:\t %s\n" % (b) ))
run
|
edit
|
history
|
help
0
Hesap makinesi
Variables mutables e inmutables
Hello
Removing punctuation from strings
If else if in 2 ways
Assignment-3c
test2.py
Q2
global 4
super and overriding