09 Iteration2
09 Iteration2
Iteration 2 2
Concepts in this slide:
Comparing the syntax of
both loop constructs.
Review: Syntax of loops
a boolean expression
denoting whether to iterate
through the body of the
loop one more time.
while continuation_condition :
statement1
…
statementN
Iteration 2 3
Flow charts for two
loop constructs True continuation False
_condition
statement1
while while
…
loop
body
statementN
for for
…
loop
body
statementN
Iteration 2 4
Concepts in this slide:
Review: sumBetween Using the iteration table to
reason about a problem.
Iteration 2 6
Concepts in this slide:
Two nested loops: the
Nested loops for printing outer and inner loop.
Iteration 2 7
Nested Loop Exercises
Conditionals can appear anywhere in loops.
Predict the printed output of the following loops.
(Answers are in the notebook solutions.)
Iteration4-10
2 10
Avoiding Nested Loops with Functions
Encapsulating the inner loop into a separate function eliminates
the loop nesting and can make programs easier to read.
# Our old friend countVowels from Lec 08 encapsulates
# the inner loop of the nested loop example with vowels
def countVowels(word):
counter = 0
for letter in word:
if isVowel(letter):
counter += 1
return counter
Iteration 2 12
Exercise: Nested Loops with graphics
Here's a picture involving a grid of randomly colored circles with
radius = 50.
This picture is created using two nested for loops. How would you
do that? You can find the answers in the notebook!
(-200, 200)
(-100, 100)
(0, 0)
Iteration 2 13
Exercise: Triangles of Circles
Which of the 4 triangular
patterns of circles is created
by the following function?
colors = ["LightSkyBlue", "LightPink",
"LightSeaGreen", "PaleVioletRed"]
reset()
noTrace()
for x in coords:
for y in coords:
if y <= x:
teleport(x, y)
color(random.choice(colors))
begin_fill()
drawCircle(radius)
end_fill()
showPicture()
Imagine you have a list of numbers that you want to sort by swapping two
adjacent (neighbor) items every time one is smaller than the other. This is a
famous algorithm known as the “bubble sort”, and is usually implemented via
nested for loops. If you’re curious, read this page. You’ll learn how to implement
bubble sort in CS 230.
tempVal = nums[0]
nums[0] = nums[1]
nums[1] = tempVal
Iteration 2 15
Concepts in this slide:
Simultaneous assignment It is possible to assign
values to multiple
In Python, we can assign values to many variables at once, here are some
examples, that you should try in the console:
step n sumSoFar
In [3]: sumHalvesBroken(22) 0 22 0
Out[3]: 19 1 11 11
2 5 16
Important: 3 2 18
If update rules involve rules 4 1 19
where state variables are 5 0 19
dependent on one another, be
very careful with the order of
updates.
Iteration 2 17
Simultaneous update example:
Greatest Common Divisor algorithm
o The greatest common divisor (gcd) of
integers a and b is the largest integer that
divides both a and b
o Eg: gcd(84, 60) is 12
o Euclid (300 BC) wrote this algorithm to compute the GCD:
o Given a and b, repeat the following steps until b is 0.
o Let the new value of b be the remainder of dividing a by b
o Let the new value of a be the old value of b
o … this is a perfect opportunity
for a while loop. step a b
0 84 60
1 60 24
2 24 12
3 12 0
Iteration 2 18
Simultaneous update (e.g., gcd)
step a b step a b step a b
0 84 60 0 33 24 0 33 7
1 60 24 1 24 9 1 7 5
2 24 12 2 9 6 2 5 2
3 12 0 3 6 3 3 2 1
4 3 0 4 1 0
Iteration 2 19
Fixing simultaneous update
# Assume a >= b > 0 # Assume a >= b > 0
def gcdFixed1(a, b): def gcdFixed2(a, b):
while b != 0: while b != 0:
prevA = a prevA = a
prevB = b prevB = b
a = prevB b = prevA % prevB
b = prevA % prevB a = prevB
return a return a
To notice:
- Functions 1&2 use temporary variables to store
values before updates.
- Function 3 assigns multiple values in one step.
Iteration 2 20
Test your knowledge
1. The sumBetween solution in slide 5 has an iteration table with three
state variables. How will the iteration table look like if the solution is
written with a for loop?
2. If we want to print out the entire multiplication table for 1 to 10, how
many times will the print statement in slide 7 be executed?
3. What would be the final value of counter in slide 9, if we move the
assignment statement before the outer for loop?
4. What results will be printed in slide 9 if the counter assignment statements
moves within the inner loop?
5. For the exercise in slide 12, try to draw a flow chart diagram like the one in
slide 10, before writing code to solve the problem.
6. What is an alternative way of writing the function in slide 17, which leads
to the same gotcha?
7. If you type 0, 1, 2 in the Python console, what kind of type will Python
assign to this sequence of numbers? How does that help for simultaneous
assignments?
Iteration 2 21