06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

142 Classes and functions<br />

def increment(time, seconds):<br />

time.seconds = time.seconds + seconds<br />

if time.seconds >= 60:<br />

time.seconds = time.seconds - 60<br />

time.minutes = time.minutes + 1<br />

if time.minutes >= 60:<br />

time.minutes = time.minutes - 60<br />

time.hours = time.hours + 1<br />

The first line performs the basic operation; the remainder deals <strong>with</strong> the special<br />

cases we saw before.<br />

Is this function correct? What happens if the parameter seconds is much greater<br />

than sixty? In that case, it is not enough <strong>to</strong> carry once; we have <strong>to</strong> keep doing it<br />

until seconds is less than sixty. One solution is <strong>to</strong> replace the if statements <strong>with</strong><br />

while statements:<br />

def increment(time, seconds):<br />

time.seconds = time.seconds + seconds<br />

while time.seconds >= 60:<br />

time.seconds = time.seconds - 60<br />

time.minutes = time.minutes + 1<br />

while time.minutes >= 60:<br />

time.minutes = time.minutes - 60<br />

time.hours = time.hours + 1<br />

This function is now correct, but it is not the most efficient solution.<br />

As an exercise, rewrite this function so that it doesn’t contain any<br />

loops.<br />

As a second exercise, rewrite increment as a pure function, and write<br />

function calls <strong>to</strong> both versions.<br />

13.4 Which is better?<br />

Anything that can be done <strong>with</strong> modifiers can also be done <strong>with</strong> pure functions.<br />

In fact, some programming languages only allow pure functions. There is some<br />

evidence that programs that use pure functions are faster <strong>to</strong> develop and less errorprone<br />

than programs that use modifiers. Nevertheless, modifiers are convenient<br />

at times, and in some cases, functional programs are less efficient.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!