42
Chapter 3
I
Recursion
The stack
This section
covers the
call stack
. It’s an important concept
in programming. The call stack
is an important concept in
general programming, and it’s also
important to understand
when using recursion
.
Suppose you’re throwing a barbecue. You
keep a todo list for the
barbecue, in the form of a stack of sticky notes.
Remember back when we talked about arrays and lists,
and you had a todo list?
You could add todo items
anywhere to the list or delete random items. The stack of
sticky notes is much simpler.
When you insert an item,
it gets added to the top of the list. When you read an item,
you
only read the topmost item, and it’s taken off the list. So your todo
list has only two actions:
push
(insert) and
pop
(remove and read).
Let’s see the todo list in action.
This
data structure is called a
stack
. The stack is a simple data structure.
You’ve been using a stack this whole time without realizing it!
43
The stack
The call stack
Your computer uses a
stack internally called the
call stack.
Let’s see it in
action. Here’s a simple function:
def greet(name):
print “hello, “ + name + “!”
greet2(name)
print “getting ready to say bye...”
bye()
This function greets you and then calls two other functions. Here are
those two functions:
Dostları ilə paylaş: