daily pastebin goal
24%
SHARE
TWEET

Untitled

a guest Jan 20th, 2019 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import re, math
  2.  
  3. class calculator(object):
  4.     def __init__(self):
  5.         self.error    = None
  6.         self.intRegex = re.compile(r'\b[\d\.]+\b')
  7.    
  8.     def _return(self, value, error=None):
  9.         if error:
  10.             self.error = error
  11.         return value
  12.    
  13.     def _safeEval(self, expr, symbols={}):
  14.         return eval(expr, dict(__builtins__=None), symbols)
  15.    
  16.     def _toFloat(self, match):
  17.         group = match.group()
  18.         if group.find('.') == -1:
  19.             return group + '.0'
  20.         return group
  21.    
  22.     def calc(self, expr, advanced=False):
  23.         self.error = None
  24.         expr       = expr.replace('^','**')
  25.         expr       = self.intRegex.sub(self._toFloat, expr)
  26.         try:
  27.             if advanced:
  28.                 return self._return(self._safeEval(expr, vars(math)))
  29.             else:
  30.                 return self._return(self._safeEval(expr))
  31.         except Exception, e:
  32.             return self._return(None, error=e)
  33.            
  34.     def fancyCalc(self, expr, advanced=False):
  35.         result = self.calc(expr, advanced=advanced)
  36.         if not result:
  37.             return "Error [{1}]: `{0}`".format(self.error, self.error.__class__.__name__)
  38.         else:
  39.             return result
  40.                
  41. calc = calculator()
  42. for equation in ["2+2","test"]:
  43.     print "Result for equation `{0}` is: {1}".format(equation, calc.fancyCalc(equation))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top