Guest User

Untitled

a guest
Jan 23rd, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. """Simple clock implementation which supports basic functions like
  2. addition and subtracting minutes. Time overflows are supported.
  3. """
  4.  
  5. # number of minutes of a day
  6. day_minutes = 24 * 60
  7.  
  8.  
  9. class Clock():
  10. def __init__(self, hours, minutes):
  11. # handle internal state with minutes. For output:
  12. # hours:minutes are calculated on the fly
  13. self.minutes = hours * 60 + minutes
  14.  
  15. def add(self, minutes):
  16. self.minutes = (self.minutes + (minutes % day_minutes)) % day_minutes
  17.  
  18. def subtract(self, minutes):
  19. normalized_minutes = minutes % day_minutes
  20. if self.minutes - normalized_minutes > 0:
  21. self.minutes = self.minutes - normalized_minutes
  22. else:
  23. difference = normalized_minutes - self.minutes
  24. self.minutes = day_minutes - difference
  25.  
  26. def __str__(self):
  27. h = self.minutes // 60
  28. m = self.minutes % 60
  29. # format time like DD:DD, pads single digits with zero, e.g. 08:05
  30. return "{0:02d}:{1:02d}".format(h, m)
  31.  
  32.  
  33. def test():
  34. c = Clock(8, 0)
  35. assert str(c) == "08:00"
  36.  
  37. c.add(20)
  38. assert str(c) == "08:20"
  39.  
  40. c.subtract(30)
  41. assert str(c) == "07:50"
  42.  
  43. c = Clock(23, 30)
  44. c.add(60)
  45. assert str(c) == "00:30"
  46.  
  47. c.subtract(40)
  48. assert str(c) == "23:50"
  49.  
  50. c.add(25 * 60)
  51. assert str(c) == "00:50"
  52.  
  53. c.subtract(25 * 60)
  54. assert str(c) == "23:50"
Add Comment
Please, Sign In to add comment