39
Recursion
Here’s one approach.
1. Make a pile of boxes to look through.
2. Grab a box, and look through it.
3.
If you find a box, add it to the pile to look through later.
4.
If you find a key, you’re done!
5. Repeat.
Here’s an alternate approach.
1. Look through the box.
2. If you find a box, go to step 1.
3. If you find a key, you’re done!
40
Chapter 3
I
Recursion
Which approach seems easier to you? The first approach uses a
while
loop. While the pile isn’t empty, grab a box and look through it:
def look_for_key(main_box):
pile = main_box.make_a_pile_to_look_through()
while pile is not empty:
box = pile.grab_a_box()
for item in box:
if item.is_a_box():
pile.append(item)
elif item.is_a_key():
print “found the key!”
The second way uses recursion.
Recursion
is where a function calls itself.
Here’s the second way in pseudocode:
Dostları ilə paylaş: