Skip to content

Instantly share code, notes, and snippets.

@gerlacdt
Last active January 22, 2019 21:10
Show Gist options
  • Save gerlacdt/9f90ece4561fae9f0e83661c3ebf4a23 to your computer and use it in GitHub Desktop.
Save gerlacdt/9f90ece4561fae9f0e83661c3ebf4a23 to your computer and use it in GitHub Desktop.
"""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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment