t475.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. def helper(got, expect):
  2. if got == expect:
  3. print True
  4. else:
  5. print False, expect, got
  6. class Squares:
  7. def __init__(self, max):
  8. self.max = max
  9. self.sofar = []
  10. def __len__(self): return len(self.sofar)
  11. def __getitem__(self, i):
  12. if not 0 <= i < self.max: raise IndexError
  13. n = len(self.sofar)
  14. while n <= i:
  15. self.sofar.append(n*n)
  16. n += 1
  17. return self.sofar[i]
  18. class Counter:
  19. class CounterIterator:
  20. def __init__(self, c):
  21. self.count = 0
  22. self.c = c
  23. def next(self):
  24. self.count += 1
  25. if self.count < self.c.stop:
  26. return self.count
  27. raise StopIteration
  28. def __iter__(self):
  29. return self
  30. def __init__(self, stop):
  31. self.count = 0
  32. self.stop = stop
  33. def __iter__(self):
  34. return self.CounterIterator(self)
  35. helper(sum([]), 0)
  36. helper(sum(range(2,8)), 27)
  37. # helper(sum(iter(range(2,8))), 27) # iter not defined
  38. # helper(sum(Squares(10)), 285) # can't iterate w/o specific __iter__ method
  39. # helper(sum(iter(Squares(10))), 285) # iter not defined
  40. helper(sum([[1], [2], [3]], []), [1, 2, 3])
  41. helper(sum([[1,2],[3,4]],[5,6]), [5, 6, 1, 2, 3, 4])
  42. helper(sum(((1,2,3),(4,5)),(6,7)),(6, 7, 1, 2, 3, 4, 5))
  43. helper(sum(Counter(10), 5), 50)
  44. # error testing -- all of these should throw a TypeError
  45. # print sum(1,2,3,4)
  46. # print sum([1,2,3,'7'])
  47. # print sum([1,2,3],1.7)
  48. # print sum([1,2,3],'8')
  49. # print sum([1,2,3],[2,3])
  50. # print sum([1,2,3],{1:2})