Grokking Algorithms


def countdown(i): print i if



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

def countdown(i):
print i
if i <= 0: 
Base case
return
else:
Recursive case
countdown(i-1)
Now the function works as expected. It goes something like this.
Infinite loop


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:

Yüklə 348,95 Kb.

Dostları ilə paylaş:
1   ...   24   25   26   27   28   29   30   31   ...   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