Consider the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def count(word, letter):
total = 0
for i in range(len(word)):
if word[i] == letter:
total = total + 1
# STOP DRAWING: show the stack just before the return statement
return total
def main():
string = "eyes"
search = "e"
answer = count(string, search)
print("The answer is %d" % (answer))
main()
Follow these steps to draw the stack:
-
Draw the empty stack and the heap.
-
When a function is called, create a stack frame for the function and put the frame on top of the stack. Usually, the first function called is
main
.-
Allocate parameters, if any, on the stack. The
main
function typically does not have parameters but many other functions do. -
Allocate variables used in the function. For very large programs, you may want to skip drawing loop variables because they change frequently and can clutter your diagram. However, you should get in the habit of including them until you are comfortable enough to understand when they can be excluded.
-
Execute the function line-by-line.
-
If another function is called, repeat at step 2.
-
If the function has a
return
value, we say that the function evaluates to be that value. Be sure to set the variable in the calling function to the returned value, if applicable.
-
-
When you reach the end of the function, remove it from the stack.
-
-
Continue executing the function that is now on top of the stack. If the stack is empty, the program is complete.
Below are the steps for drawing the stack for the code shown above. Line numbers are included so you can see how each line impacts the drawing. Try drawing the stack yourself and see if you get the same drawing!
Step | Line # | What happens to the stack diagram |
---|---|---|
1 |
16 |
Put a frame for |
2 |
11 |
Put the variable |
3 |
12 |
put |
Figure 1. Stack Diagram after step 3.
|
||
4 |
13 |
The |
5 |
1 |
Put parameter |
6 |
1 |
Put parameter |
Figure 2. Stack Diagram after step 6.
|
||
7 |
2 |
Put the local variable |
8 |
3 |
In each iteration of the for loop, the loop variable |
Figure 3. Stack Diagram after step 6.
|
||
9 |
5 |
When |
10 |
3 |
At the next iteration of the for loop, draw a new arrow from |
11 |
3 |
At the next iteration of the for loop, draw a new arrow from |
Figure 4. Stack Diagram after step 11.
|
||
12 |
5 |
When |
13 |
3 |
At the next iteration of the for loop, draw a new arrow from |
14 |
7 |
We reach the comment that says |
Figure 5. Stack Diagram after step 14.
|
||
15 |
8 |
If we were to continue with the |
16 |
13 |
Draw an arrow from |
17 |
14 |
The string |
Figure 6. Stack Diagram after step 17.
|
||
18 |
15 |
The end of |
Figure 7. Stack Diagram after step 18.
|