Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class calcerr(ValueError):
- '''mistake'''
- class oper2:
- def __init__(self,func,num_args=2):
- self.func=func
- self.num_args=num_args
- class calc1:
- def __init__(self):
- import operator as oper
- self.oper_list = {'+':oper2(oper.add),
- "-":oper2(oper.sub),
- "*":oper2(oper.mul),
- "/":oper2(oper.truediv),
- "^":oper2(oper.pow),
- "%":oper2(oper.mod),
- "abs":oper2(oper.abs,num_args=1),
- }
- self.eval_q=[]
- def clear_q(self):
- self.eval_q=[]
- def print_q(self):
- print(self.eval_q)
- def add_custom(self,filename):
- import json
- with open(filename) as file:
- data=json.loads(file.read())
- import math
- for key,module in data.items():
- if hasattr(math, module):
- self.oper_list[key] = oper2(getattr(math, module), num_args=1)
- def addto_q(self,val):
- self.eval_q.append(self.convert_user(val))
- if self.isoperation(self.eval_q[-1]):
- result = self.eval_q.pop()
- num_args = self.oper_list[result].num_args
- if len(self.eval_q)<num_args:
- raise calcerr('not enough val')
- args = []
- for i in range(num_args):
- args.append(self.eval_q.pop())
- result = calc.perf_oper(result,args)
- self.eval_q.append(result)
- def print_oper(self):
- print('operations list:')
- for x in self.oper_list.keys():
- print(x, end=" ")
- print('')
- def isoperation(self,val):
- if val in self.oper_list.keys():
- return True
- else:
- return False
- def convert_user(self,value):
- if self.isfloat(value):
- return float(value)
- elif self.isoperation(value):
- return value
- else:
- raise calcerr('invalid')
- def perf_oper(self,op,val):
- if self.isoperation(op):
- return self.oper_list[op].func(*val)
- return op
- @staticmethod
- def isfloat(value):
- try:
- tmp = float(value)
- return True
- except ValueError:
- return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement