fork download
  1. import random
  2. import time
  3.  
  4. BASE = 3
  5.  
  6.  
  7. class RatioInt(list):
  8.  
  9. def __init__(self, value=[], base=10):
  10. assert all(
  11. val < base for val in value), 'Elements must be less than base. Base = %s' % base
  12.  
  13. super(RatioInt, self).__init__(reversed(value))
  14. self.base = base
  15.  
  16. def __add__(self, other):
  17. out = [0 for _ in range(max(len(self), len(other)))]
  18. i = 0
  19. c = 0
  20.  
  21. while i < len(out):
  22. temp = self[i] + other[i] + c
  23. out[i] = (temp % self.base)
  24. c = temp // self.base
  25.  
  26. i += 1
  27.  
  28. if c:
  29. out.append(c)
  30.  
  31. return RatioInt(out, self.base)
  32.  
  33. def __mod__(self, val):
  34. '''
  35. Возвращает val-последних символов.
  36. '''
  37. return self[-val:]
  38.  
  39. def __getitem__(self, key):
  40. try:
  41. return super(RatioInt, self).__getitem__(key)
  42. except IndexError:
  43. return 0
  44.  
  45. def __str__(self):
  46. return ''.join(str(elem) for elem in self) + '(%s)' % self.base
  47.  
  48.  
  49. def timing(func):
  50. def _f(*args, **kwargs):
  51. start = time.time()
  52. out = func(*args, **kwargs)
  53. print('It took %2.6ss' % (time.time() - start))
  54. return out
  55.  
  56. return _f
  57.  
  58.  
  59. @timing
  60. def test_ariphmetic():
  61. for _ in range(10 ** 5):
  62. base = random.randint(2, 10)
  63. a = RatioInt([random.randint(0, base - 1) for _ in range(3)], base)
  64. b = RatioInt([random.randint(0, base - 1) for _ in range(3)], base)
  65. a += b
  66. # print('%s + %s = %s' % (a, b, a + b))
  67.  
  68.  
  69. if __name__ == '__main__':
  70. test_ariphmetic()
  71.  
Success #stdin #stdout 2.71s 10976KB
stdin
Standard input is empty
stdout
It took 2.6850s