Python
Programming Exercises, Gently Explained
33
i = ____
while i < len(____):
# If index i in text is the start of the oldText pattern, add
# the replacement text:
if text[i:i + len(____)] == oldText:
# Add the replacement text:
replacedText += ____
# Increment i by the length of oldText:
i += len(____)
# Otherwise, add the characters at text[i] and increment i by 1:
else:
replacedText += ____[i]
i += ____
return replacedText
The complete solution for this exercise is given in Appendix A and
https://invpy.com/
findandreplace.py. You can view each step of this program as it runs under a debugger at
https://invpy.com/
findandreplace-debug/.
34
E X E R C I S E # 1 1 : H O U R S , M I N U T E S ,
S E C O N D S
getHoursMinutesSeconds(90)
→
'1m 30s'
Websites often use relative timestamps such as ―3 days ago‖ or ―about 3h ago‖
so the user
doesn’t need to compare an absolute timestamp to the current time. In this exercise, you write a
function that converts a number of seconds into a string
with the number of hours, minutes, and
seconds.
Exercise Description
Write a getHoursMinutesSeconds() function that has a totalSeconds parameter. The
argument for this parameter will be the number of seconds to be translated into the number of hours,
minutes, and seconds. If the amount for the hours, minutes, or seconds is zero, don’t show it: the
function should return '10m' rather than '0h 10m 0s'.
The only exception is that
getHoursMinutesSeconds(0)
should return '0s'.
These Python assert statements stop the program if their condition is False. Copy them to
the bottom of your solution program. Your solution is correct if the following assert statements’
conditions are all True:
assert getHoursMinutesSeconds(30) == '30s'
assert getHoursMinutesSeconds(60) == '1m'
assert getHoursMinutesSeconds(90) == '1m 30s'
assert getHoursMinutesSeconds(3600) == '1h'
assert getHoursMinutesSeconds(3601) == '1h 1s'
assert getHoursMinutesSeconds(3661) == '1h 1m 1s'
assert getHoursMinutesSeconds(90042) == '25h 42s'
assert getHoursMinutesSeconds(0) == '0s'
For an additional challenge, break up 24 hour periods into days with a ―d‖ suffix. For example,
getHoursMinutesSeconds(90042)
would return '1d 1h 42s'.
Try to write a solution based on the information in this description. If you still
have trouble
solving this exercise, read the
Solution Design and
Special Cases and Gotchas sections for
additional hints.
Python Programming Exercises, Gently Explained
35
Prerequisite concepts: join(), append(), lists, string concatenation, while loops
Dostları ilə paylaş: