Question: Rewrite increment as a pure function, and write function calls to both
ID: 3619804 • Letter: Q
Question
Question: Rewrite increment as a pure function,and write function calls to both versions.
--
The reading for this question is posted below:
---
Modifiers:
There are times when it is useful for a function to modify one or more of the
objects it gets as arguments. Usually, the caller keeps a reference to the objects
it passes, so any changes the function makes are visible to the caller. Functions
that work this way are called modifiers.
increment, which adds a given number of seconds to a Time object, would be
written most naturally as a modifier. A rough draft of the function looks like this:
def increment(time, seconds):
time.seconds = time.seconds + seconds
if time.seconds >= 60:
time.seconds = time.seconds - 60
time.minutes = time.minutes + 1
if time.minutes >= 60:
time.minutes = time.minutes - 60
time.hours = time.hours + 1
The first line performs the basic operation; the remainder deals with the special
cases we saw before.
Is this function correct? What happens if the parameter seconds is much greater
than sixty? In that case, it is not enough to carry once; we have to keep doing it
until seconds is less than sixty. One solution is to replace the if statements with
while statements:
def increment(time, seconds):
time.seconds = time.seconds + seconds
while time.seconds >= 60:
time.seconds = time.seconds - 60
time.minutes = time.minutes + 1
while time.minutes >= 60:
time.minutes = time.minutes - 60
time.hours = time.hours + 1
This function is now correct, but it is not the most efficient solution.
Explanation / Answer
Time class: class time: hours = 12; minutes = 00; seconds = 00; increment function(It might be efficient): def increment(time, seconds): time.seconds = time.seconds + seconds minutes = time.seconds/60; time.seconds = time.seconds%60; time.minutes = time.minutes + minutes; hours = time.minutes/60; time.minutes = time.minutes % 60; time.hours = time.hours + hours;
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.