Grokking Algorithms


def look_for_key(box): for



Yüklə 348,95 Kb.
Pdf görüntüsü
səhifə27/122
tarix05.12.2023
ölçüsü348,95 Kb.
#173611
1   ...   23   24   25   26   27   28   29   30   ...   122
grokking-algorithms-illustrated-programmers-curious

def look_for_key(box):
for item in box:
if item.is_a_box():
look_for_key(item) 
Recursion!
elif item.is_a_key():
print “found the key!”
Both approaches accomplish the same thing, but the second approach 
is clearer to me. Recursion is used when it makes the solution clearer. 
There’s no performance benefit to using recursion; in fact, loops are 
sometimes better for performance. I like this quote by Leigh Caldwell 
on Stack Overflow: “Loops may achieve a performance gain for 
your program. Recursion may achieve a performance gain for your 
programmer. Choose which is more important in your situation!”
1
Many important algorithms use recursion, so it’s important to 
understand the concept.
Base case and recursive case
Because a recursive function calls itself, it’s easy to write a 
function incorrectly that ends up in an infinite loop. For 
example, suppose you want to write a function that prints a countdown, 
like this:
> 3...2...1
1
 http://stackoverflow.com/a/72694/139117.


41
Base case and recursive case
You can write it recursively, like so:
def countdown(i):
print i
countdown(i-1)
Write out this code and run it. You’ll notice a problem: this function 
will run forever!
> 3...2...1...0...-1...-2...
(Press Ctrl-C to kill your script.)
When you write a recursive function, you have to tell it when to stop 
recursing. That’s why 
every recursive function has two parts: the base 
case, and the recursive case.
The recursive case is when the function calls 
itself. The base case is when the function doesn’t call itself again … so it 
doesn’t go into an infinite loop.
Let’s add a base case to the countdown function:

Yüklə 348,95 Kb.

Dostları ilə paylaş:
1   ...   23   24   25   26   27   28   29   30   ...   122




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

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin