Solving for edge cases on "Add mins to 24 hour clock" – certain edge cases failing

Question:

I’m trying to solve this challenge:
https://profound.academy/python-introduction/jAdU8ObJbCCYPG45hJWz

I have solved it for all inputs listed, from the public info on the course (hours, minutes, added minutes):

  • 14, 28, 75 = 15:43
  • 14, 28, 1440 = 14:28
  • 7, 50, 5320 = 0:30
  • 23, 58, 2 = 0:0
  • (In comments): 18, 12, 1139 = 13:11

However, one or more of the unlisted (private) edge cases is still failing. Here is my Python code:

# Take input, truncating to unit
hours = int(input()) % 24
mins = int(input()) % 60 
addMins = int(input()) % 1440 

# Add mins clock has been stuck
newMins = (mins + addMins) % 60
newHours =  hours + (addMins // 60)
newHours = newHours % 23

print(newHours, ':', newMins, sep='')
Asked By: SamAndrew81

||

Answers:

Your calculation of newHours is wrong (you have the right idea, but there’s a bug there) – there are 24 hours a day, so you should take modulo 24, not 23:

newHours = newHours % 24

EDIT:
There’s another bug I missed there. It misses the fact that when the new minutes overflow over 60 they should add an hour. Let’s clarify this with a simple example – assume the clock shows 00:45, and you move it forward 20 minutes. 45+20=65, so you’d want the minutes to display 65 % 60 = 5, but you’ve also moved an hour forward – it’s not 00:05, but 01:05.

To express this in Python:

newMins = mins + addMins
newHours =  hours + (newMins // 60)
newHours = newHours % 24
newMins = newMins % 60
print(newHours, ':', newMins, sep='')
Answered By: Mureinik

i think the problem is here

newHours =  hours + (addMins // 60)
newHours = newHours % 23

consider that hours is 23 and addMins 60+ newHours is now 24
so if you make newHours = newHours % 23 you get 1 : minutes , wich is not the desired answer , it should be newHours = newHours % 24

Answered By: ach2ashes
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.