P ython p rogramming e xercises



Yüklə 1,51 Mb.
Pdf görüntüsü
səhifə29/124
tarix14.05.2023
ölçüsü1,51 Mb.
#113537
1   ...   25   26   27   28   29   30   31   32   ...   124
PythonProgrammingExercisesGentlyExplained

Solution Design 
One hour is 3600 seconds, one minute is 60 seconds, and one second is… 1 second. Our 
solution can have variables that track the number of hours, minutes, and seconds in the final result 
with variables hours, minutes, and seconds. The code subtracts 3600 from the totalSeconds 
while increasing hours by 1. Then the code subtracts 60 from totalSeconds while increasing 
minutes
by 1. The seconds variable can then be set to whatever remains in totalSeconds. 
After calculating hours, minutes, and seconds, you should convert those integer amounts into 
strings with respective 'h', 'm', and 's' suffixes like '1h' or '30s'. Then you can append them 
to a list that initially starts as empty. Then the join() list method can join these strings together with 
a single space separating them: from the list ['1h', '30s'] to the string '1h 30s'. For example, 
enter the following into the interactive shell: 
>>> hms = ['1h', '30s'] 
>>> ' '.join(hms) 
'1h 30s' 
The function then returns this space-separated string. 
If you’re unfamiliar with the join() string method, you can enter help(str.join) into the 
interactive shell to view its documentation, or do an internet search for ―python join‖. 
Special Cases and Gotchas 
The first special case your function should check for is if the totalSeconds parameter is set to 
0. In this case, the function can immediately return '0s'. 
The final result string shouldn’t include hours, minutes, or seconds if the amount of those is zero. 
For example, your program should return '1h 12s' but not '1h 0m 12s'. 
Also, it’s important to subtract the larger amounts first. Otherwise, you would, for example, 
increase hours by 0 and minutes by 120 instead of increase hours by 2 and minutes by 0. 
Now try to write a solution based on the information in the previous sections. If you still have 
trouble solving this exercise, read the Solution Template section for additional hints. 

Yüklə 1,51 Mb.

Dostları ilə paylaş:
1   ...   25   26   27   28   29   30   31   32   ...   124




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2025
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin