Understanding stack diagrams helps you understand how the computer works, and why python does what it does. It will also be vary valuable in week 10 when we learn recursion (functions calling multiple copies of themselves).
Take a look at the following program and see if you can figure out what it will do and what it will print to the screen.
def main():
S = "we love comp sci!"
L = list(S)
numVowels = capitalizeVowels(L)
newS = "".join(L)
print(numVowels)
print(newS)
def capitalizeVowels(mylist):
"""count and capitalize the vowels"""
count = 0
for i in range(len(mylist)):
if isVowel(mylist[i]):
mylist[i] = mylist[i].upper()
count += 1
return count
def isVowel(ch):
"""return True if ch is a vowel, False if not"""
vowels = "aeiou"
if ch.lower() in vowels:
return True
else:
return False
main()
After you think you know what it will do, copy the text of the program into the python tutor and visualize its execution. Here are some things to note as you run the program:
main()
is run, a blue box is put on "top" of the stack,
with any variables declared in main()
shown in the box (or
with arrows pointing to the data of the variable)capitalize()
is called from main()
, another blue box
is put on "top" of the stack. The function on top of the stack
is the function that is currently executingcapitalize()
, the mylist
variable points to the same data
that L
in main()
points to. This means any changes made to
mylist[i]
will affect L
in main()
isVowel()
is called, there is a blue box for it put
on top of the stack. When isVowel()
ends, the box (and all variables
in the box!) disappears and we drop back to capitalizeVowels()
, the
function that called isVowel()
The final output of the program is this:
5
wE lOvE cOmp scI!
Do you understand how L
was changed in main()
, even though capitalizeVowels()
did not return mylist
?
Write a function called listmax(L,maxval)
that has two parameters: a list (L
)
of numbers and a maximum value (maxval
). The function should reset any
values in L
that are above maxval
. For example:
listmax(L,255)
with L=[100,200,300]
should change L
to be [100,200,255]
listmax(L,100)
with L=[100,200,300]
should change L
to be [100,100,100]