Advertisement
jensyao

calc.py

Feb 9th, 2017
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.31 KB | None | 0 0
  1. class calcerr(ValueError):
  2.     '''mistake'''
  3. class oper2:
  4.     def __init__(self,func,num_args=2):
  5.         self.func=func
  6.         self.num_args=num_args
  7. class calc1:
  8.     def __init__(self):
  9.         import operator as oper
  10.         self.oper_list = {'+':oper2(oper.add),
  11.                      "-":oper2(oper.sub),
  12.                      "*":oper2(oper.mul),
  13.                      "/":oper2(oper.truediv),
  14.                      "^":oper2(oper.pow),
  15.                      "%":oper2(oper.mod),
  16.                      "abs":oper2(oper.abs,num_args=1),
  17.                     }
  18.         self.eval_q=[]
  19.     def clear_q(self):
  20.         self.eval_q=[]
  21.     def print_q(self):
  22.         print(self.eval_q)
  23.     def add_custom(self,filename):
  24.         import json
  25.         with open(filename) as file:
  26.             data=json.loads(file.read())
  27.         import math
  28.         for key,module in data.items():
  29.             if hasattr(math, module):
  30.                 self.oper_list[key] = oper2(getattr(math, module), num_args=1)
  31.     def addto_q(self,val):
  32.         self.eval_q.append(self.convert_user(val))
  33.         if self.isoperation(self.eval_q[-1]):
  34.             result = self.eval_q.pop()
  35.             num_args = self.oper_list[result].num_args
  36.             if len(self.eval_q)<num_args:
  37.                 raise calcerr('not enough val')
  38.             args = []
  39.             for i in range(num_args):
  40.                 args.append(self.eval_q.pop())
  41.             result = calc.perf_oper(result,args)
  42.             self.eval_q.append(result)
  43.     def print_oper(self):
  44.         print('operations list:')
  45.         for x in self.oper_list.keys():
  46.             print(x, end=" ")
  47.         print('')
  48.        
  49.     def isoperation(self,val):
  50.          if val in self.oper_list.keys():
  51.             return True
  52.          else:
  53.             return False
  54.  
  55.     def convert_user(self,value):
  56.         if self.isfloat(value):
  57.             return float(value)
  58.         elif self.isoperation(value):
  59.             return value
  60.         else:
  61.             raise calcerr('invalid')
  62.    
  63.     def perf_oper(self,op,val):
  64.         if self.isoperation(op):
  65.             return self.oper_list[op].func(*val)
  66.         return op
  67.     @staticmethod
  68.     def isfloat(value):
  69.         try:
  70.             tmp = float(value)
  71.             return True
  72.         except ValueError:
  73.             return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement