Advertisement
Guest User

Really stupid summation

a guest
Oct 15th, 2019
1,363
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. inf = '∞'
  2.  
  3. class expression:
  4.  
  5.     def __init__(self, text, *variables):
  6.         self.text = text
  7.         self.variables = variables
  8.  
  9.     def do_operation(a, b, operator):
  10.         variables = set()
  11.         if isinstance(a, expression):
  12.             variables.add(a.variables)
  13.         if isinstance(b, expression):
  14.             variables.add(b.variables)
  15.         return expression(
  16.             f'({a}{operator}{b})',
  17.             *variables
  18.         )
  19.  
  20.     operators = {
  21.         '+': 'add',
  22.         '-': 'sub',
  23.         '*': 'mul',
  24.         '/': 'truediv',
  25.         '**': 'pow',
  26.         '//': 'div',
  27.     }
  28.     for operator, funcname in operators.items():
  29.         locals()[f'__{funcname}__'] = (lambda _operator: lambda self, other: expression.do_operation(self, other, _operator))(operator)
  30.         locals()[ f'__r{funcname}__'] = (lambda _operator: lambda self, other: expression.do_operation(other, self, _operator))(operator)
  31.  
  32.     def __str__(self):
  33.         return self.text
  34.  
  35. class sum_obj:
  36.    
  37.     def __init__(self):
  38.         from string import ascii_lowercase
  39.         globals().update(
  40.             {c: expression(c, c) for c in ascii_lowercase}
  41.         )
  42.  
  43.     def __ror__(self, other):
  44.         self.variables = {}
  45.         self.count = 10_000 if other == inf else other
  46.         return self
  47.  
  48.     def __call__(self, func):
  49.         self.func = func
  50.         return self
  51.  
  52.     def __setattr__(self, key, value):
  53.         if len(key) == 1:
  54.            
  55.             s = 0
  56.             for i in range(self.count):
  57.                 s += eval(str(self.func), globals(), {key: value+i})
  58.             print(s)
  59.  
  60.         else:
  61.             super().__setattr__(key, value)
  62.  
  63. Σ = sum_obj()
  64.  
  65.  
  66.  
  67. (   '∞'                   \
  68. |    Σ (  1/(2**i)  )     \
  69. ).  i=1                   \
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement