Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Simple clock implementation which supports basic functions like
- addition and subtracting minutes. Time overflows are supported.
- """
- # number of minutes of a day
- day_minutes = 24 * 60
- class Clock():
- def __init__(self, hours, minutes):
- # handle internal state with minutes. For output:
- # hours:minutes are calculated on the fly
- self.minutes = hours * 60 + minutes
- def add(self, minutes):
- self.minutes = (self.minutes + (minutes % day_minutes)) % day_minutes
- def subtract(self, minutes):
- normalized_minutes = minutes % day_minutes
- if self.minutes - normalized_minutes > 0:
- self.minutes = self.minutes - normalized_minutes
- else:
- difference = normalized_minutes - self.minutes
- self.minutes = day_minutes - difference
- def __str__(self):
- h = self.minutes // 60
- m = self.minutes % 60
- # format time like DD:DD, pads single digits with zero, e.g. 08:05
- return "{0:02d}:{1:02d}".format(h, m)
- def test():
- c = Clock(8, 0)
- assert str(c) == "08:00"
- c.add(20)
- assert str(c) == "08:20"
- c.subtract(30)
- assert str(c) == "07:50"
- c = Clock(23, 30)
- c.add(60)
- assert str(c) == "00:30"
- c.subtract(40)
- assert str(c) == "23:50"
- c.add(25 * 60)
- assert str(c) == "00:50"
- c.subtract(25 * 60)
- assert str(c) == "23:50"
Add Comment
Please, Sign In to add comment