StacyM - 1 year ago 67

Python Question

I'm working on this intro to python online course. I am close to a solution to this problem which reads:

This program takes two lines of input. The first line is a "starting time" expressed in a 24-hour clock with leading zeroes, like 08:30 or 14:07. The second line is a duration D in minutes. Print out what time it will be D minutes after the starting time. For example, for input

`12:30`

47

Output:

`13:17`

Hints given:

`Break the input into hours and minutes.`

Final minutes should be (M + D) % 60.

Final hours requires //60 and % 24.

My solution so far:

`ST = input()`

STlen = len(ST)

D = int(input())

for position in range (0,STlen):

if ST[position] == ':':

H = int(ST[0:position])

M = int(ST[position+1:STlen])

#minutes section

final_min = (M+D) % 60

if final_min < 10:

finalminstr1 = str(final_min)

zeroed_finalmin_str = '0' + finalminstr1

final_min = zeroed_finalmin_str

else:

final_min = (M+D) % 60

#hours section

if D > 60:

finalhr = (D // 60) + H

elif (M+D) % 60 > 0 and H % 24 == H and D < 60:

finalhr = H+1

if finalhr == 24:

finalhr = '00'

#getting final end time ready

finalminstr = str(final_min)

finalhrstr = str(finalhr)

endtime = finalhrstr + ":" + finalminstr

print(endtime)

I think my approach is too convoluted and would waste processing time. It's also breaking when I use

`15:33`

508

as input data. The correct output should be 00:01, but I'm getting 23:01.

Any ideas on how to improve my code?

Answer Source

Note that when D > 60, such as your example broken case, you never check if `M + (D % 60) > 60`

, so you are left with your incorrect answer of 23:01.

I suppose what you actually have to check is if `M + (D % 60) > 60`

, this means that you have to increase `H`

by one, and then check if that pushes it over 24. An easy way of doing that is just altering your `if`

structure, I am not used to python, but it looks like `elif`

means `else if`

correct? if so, you could restructure that block to look like this:

```
finalhr = (D // 60) + H + ((M + (D % 60)) // 60)
finalhr = finalhr % 24
```

So if `D < 60`

, then `(D // 60)`

will be zero, and if `(M + (D % 60)) < 60`

, then `((M + (D % 60)) // 60)`

will also be zero. The second line will make `finalhr`

zero if it was equal to 24, and 1 if it was equal to 25, and so on. This should give you the correct number of hours.