NYU Entry Level Programming Questions

2022/8/21 22:28
Lesson 6.3: Looping over Nested Lists | Lessons | CS 116 Courseware | UW Online
Lesson 6.3: Looping over Nested Lists
Nested Lists and Loops
In this last lesson of the module, we discuss looping over lists of lists.
In a previous module, we considered nested lists such as this:
L = [[1,2], [], [7,8,9,10]]
In this lesson, we will discuss how to loop over these lists and give another chance to practice looping. When
we loop through a list of lists, as shown above, the list elements in a for loop are lists themselves. That is,
each thing is actually of type (listof Int). Review the example below:
1
2
3
for lst in L:
for item in lst:
##loop body to analyze inner list
Concept Check 6.3.1
1/1 point (graded)
Consider the following code:
1
L = [[1, 2], [], [7, 8, 9, 10]]
2
for M in L:
3
print(sum(M))
What is printed to the screen?
1
0
7
3
0
34
3
37
There is an error in the above code

https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?chil…
1/9
2022/8/21 22:28
Lesson 6.3: Looping over Nested Lists | Lessons | CS 116 Courseware | UW Online
Concept Check 6.3.2
1/1 point (graded)
Consider the following code:
1
L = [[1,2], [], [7,8,9,10]]
2
s = 0
3
for M in L:
4
if M != []:
5
s += M[0]
What is the value of s after the above code is executed?
0
1
7
8
37

Concept Check 6.3.3
1/1 point (graded)
Consider the following code:
1
L = [[1,2], [], [7,8,9,10]]
2
s = 0
3
for M in L:
4
for i in M:
5
s += i
What is the value of s after the above code is executed?
0
3
8
34
37

https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?chil…
2/9
2022/8/21 22:28
Lesson 6.3: Looping over Nested Lists | Lessons | CS 116 Courseware | UW Online
Concept Check 6.3.4
1/1 point (graded)
Consider the following code:
1
L = [[1,2], [], [7,8,9,10]]
2
s = 0
3
for M in L:
4
for i in M:
5
s += M[0]
What is the value of s after the above code is executed?
2
8
30
24
37

Mutating Nested Lists
Just like in the previous section however, the above template cannot be used if you want to mutate the
elements in the list. We can use a similar approach to what was done in the for loops section and iterate
over all the indices if we want to mutate a nested list.
1
## Template for List Mutation for nested lists via for loops
2
3
def mutation_template_for_loop_nested_list(L):
4
##Assume L is a (listof (listof Any))
5
for row in range(len(L)):
6
for col in range(len(L[row])):
7
L[row][col] = ##something
Concept Check 6.3.5
1/1 point (graded)
Suppose L = [[1, 2],[],[7, 8, 9, 10]] . Which of the following will access the number 1?
L[0][0]
L[1][0]
L[1][1]
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?chil…
3/9
2022/8/21 22:28
Lesson 6.3: Looping over Nested Lists | Lessons | CS 116 Courseware | UW Online
L[2][0]
L[2][3]

Concept Check 6.3.6
Write the body of a function negate_first(L, val) which consumes a list of lists of integers and a
positive integer val . The function returns None but mutates the list so that the first entry in L that
equals val becomes -val (starting from L[0][0], L[0][1],…,L[0]L[len(L[0])-1], L[1]
[0],… and so on). You must use loops and you may assume val exists in the list.
3/3 points
Attempts: 1 / Unlimited
1
def negate_first(L, val):
2
”’
3
Mutates the list so the first occurrence of val is negated
4
5
Effects: Mutates L
6
7
negate_first: (listof (listof Int)) -> None
8
Requires:
9
val occurs in L
10
11
Examples:
12
L = []
13
negate_first(L, 10) => None
14
and L is not mutated
15
16
L = [[0], [3,2,1], [] ,[17,1,9,10], [1, 2]]
17
negate_first(L, 1) => None
18
and L is mutated to:
19
[[0], [3,2,-1], [] ,[17,1,9,10], [1, 2]]
20
”’
21
for n in range(len(L)):
22
for x in range(len(L[n])):
23
if L[n][x] == val:
24
L[n][x] = – val
25
return None
26
L = [[0], [1,2,3], [] ,[17,1,9,10]]
27
negate_first(L, 1)
28
print(L)
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?chil…
4/9
2022/8/21 22:28
Lesson 6.3: Looping over Nested Lists | Lessons | CS 116 Courseware | UW Online
Correct! 3/3 points

Concept Check 6.3.7
Write the body of a function nested_max(alol) which consumes a list of lists of integers. The function
returns the largest value of the inner lists in alol . Do not use recursion of abstract list functions or the
command max . You must use loops.
3/3 points
Attempts: 1 / Unlimited
1
def nested_max(alol):
2
”’
3
Returns the largest value in alol
4
5
nested_max: (listof (listof Int)) -> Int
6
Requires:
7
alol is nonempty
8
alol[0] is nonempty
9
10
Examples:
11
nested_max([[0], [1,2,3], [] ,[17,8,9,10]]) => 17
12
nested_max([[1,5,3], [3],[35,1,2]]) =>
13
”’
14
k = alol[0][0]
15
for n in range(len(alol)):
16
for x in range(len(alol[n])):
17
if k < alol[n][x]: 18 k = alol[n][x] 19 35 return k Correct! 3/3 points  Concept Check 6.3.8 1/1 point (graded) Consider the following code: 1 def mystery(n): 2 ans = [] 3 for r in range(n): 4 row = [] 5 for c in range(n): https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?chil… 5/9 2022/8/21 22:28 Lesson 6.3: Looping over Nested Lists | Lessons | CS 116 Courseware | UW Online 6 7 8 row.append(r*c) ans.append(row) return ans Based on the code above, if we execute the code mystery(6) , how many times does line 6 run? 0 1 6 36 216  Concept Check 6.3.9 1/1 point (graded) Consider the following code: 1 def mystery(n): 2 ans = [] 3 for r in range(n): 4 row = [] 5 for c in range(n): 6 row.append(r*c) 7 8 ans.append(row) return ans Which of the below best describes what the above code does? It returns a single row of n numbers It returns a list of lists where each of the inner lists contains a single number from 1 to n It returns a list of lists where each of the inner lists contains a single number n It returns a list of lists where each of the inner lists contains contains the values from 1 to n It returns a multiplication table of size n by n  Concept Check 6.3.10 https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?chil… 6/9 2022/8/21 22:28 Lesson 6.3: Looping over Nested Lists | Lessons | CS 116 Courseware | UW Online In a list of list of integers, an even-inner-sum is the sum of all the even integers in an inner list. Write the body of a function max_even_sum(lol) which consumes a list of lists of integers and returns the maximum even-inner-sum. You may assume the list is not empty and that if an inner list is empty or does not contain even integers, it has a sum of 0. Do not use abstract list functions and do not mutate the passed parameter. 0/3 points Attempts: 8 / Unlimited 1 def max_even_sum(lol): 2 ''' 3 Returns the sum of the even integers in the inner list in lol 4 that has the maximal even integer sum 5 6 max_even_sum: (listof (listof Int)) -> Int
7
Requires: lol is non-empty
8
9
Examples:
10
max_even_sum([[]]) => 0
11
max_even_sum([[], [3], [10,1,3,5,7], [2,4,6]]) => 12
12
max_even_sum([[1,3,5,7],[-10]]) => 0
13
”’
14
k = 0
15
for n in range(len(lol)):
16
s = 0
17
for x in range(len(lol[n])):
18
if lol[n][x] % 2 == 0:
19
s = s + lol[n][x]
20
if s > k:
21
k = s
22
return k
NOTE: The due date has passed for this question. You can still submit your code for grading,
however, no marks will be rewarded.

Incorrect 0/3 points
Concept Check 6.3.11
Define the p-norm of a list of floats L = [a_0, …, a_n] to be the value given by
𝑝
𝑝
𝑝
𝑝‾
𝑎‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
+ 𝑎 + ⋯ + 𝑎‾
𝑛
1
√ 0
Write the body of a function p_norm(M, p) that consumes a non-empty (listof (listof Float)) in
M (with non-empty inner lists) and a positive integer p and returns a list containing the p-norm of each
element of M as defined above. You must use loops to solve this problem. Do not use any abstract list
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?chil…
7/9
2022/8/21 22:28
Lesson 6.3: Looping over Nested Lists | Lessons | CS 116 Courseware | UW Online
functions or recursion. Do not mutate M .
3/3 points
Attempts: 1 / Unlimited
1
def p_norm(M, p):
2
”’
3
Returns a list of the p-norms of elements of M
4
5
p_norm: (listof (listof Float)) Nat -> (listof Float)
6
Requires:
7
p > 0
8
M is non-empty
9
Each inner list of M is non-empty
10
11
12
p_norm([[0.0]], 2) => [0.0]
13
p_norm([[1.0 ,2.0 ,3.0], [3.0 ,1.0 ,2.0]], 3)
14
=> [3.3019272488946263, 3.3019272488946263]
15
”’
16
answer = []
17
for n in range(len(M)):
18
k = 0.0
19
for m in range(len(M[n])):
20
k = k + (M[n][m] ** p)
21
k = k ** (1 / p)
22
answer = answer + [k]
23

Examples:
return answer
Correct! 3/3 points
Concept Check 6.3.12
In this problem, we will use the data definition of a grid which you will see again later:
A Grid is a (listof (listof Nat)) where each of the inner lists has the same length
as the outer list.
In other words, a Grid is a two-dimensional list where the number of rows and columns are equal (think a
square matrix).
Write the body of a function column(grid, col_num) that consumes a non-empty grid and a natural
number between 0 and len(grid)-1 and returns the column numbered col_num.
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?chil…
8/9
2022/8/21 22:28
Lesson 6.3: Looping over Nested Lists | Lessons | CS 116 Courseware | UW Online
Note: Do not use abstract list functions.
3/3 points
Attempts: 1 / Unlimited
1
def column(grid, col_num):
2
”’
3
Returns the col_num column of grid
4
5
column: Grid Nat -> (listof Nat)
6
Requires:
7
grid is not empty
8
col_num [1]
12
column([[10,2],[20,1]], 1) => [2, 1]
13
”’
14
answer = []
15
for n in range(len(grid)):
answer = answer + [grid[n][col_num]]
16
17

return answer
Correct! 3/3 points
Final Thoughts
In this module, we discussed looping, which is a form of iteration. We discussed while and for loops and
how they give us a way to efficiently traverse data. Additionally, you’ve learned the differences between
these two types of loops. You should now be able to explain why looping is better than recursion in our
Python programs. Lastly, you should be comfortable with using any of our data types, including nested lists,
inside our loops.
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?chil…
9/9
2022/8/21 22:27
Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online
Lesson 6.1: while Loops
Reviewing Singleton Function
Recall the following problem from the Warm-Up Quiz:
Write a function singleton(n) which consumes an integer n and returns the list consisting
of the single element n if and only if n is a natural number and an empty list otherwise.
Your solution might have looked something like this:
1
import check
2
3
4
def singleton(n):
5
”’
6
Returns a list consisting of n if n is a natural number
7
otherwise returns empty list.
8
singleton: Int -> (listof Nat)
9
10
Example:
11
singleton(0) => [0]
12
13
”’
14
answer = []
15
if n >= 0:
answer.append(n)
16
return answer
17
18
19
check.expect(“Test 1”, singleton(0), [0])
20
check.expect(“Test 2”, singleton(-42), [])
21
check.expect(“Test 3″, singleton(4), [4])
Visualize
Reset Code
Extending Singleton
How would we extend the above function so that instead of just producing [n], it would produce the list
[n, n-1, …, 1, 0]?
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch…
1/17
2022/8/21 22:27
Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online
Concept Check 6.1.1: Countdown
Write the body of a function count_down(n) which consumes an integer n and produces the list [n,
n-1, …, 1, 0] . Do not use abstract list functions or the command range .
3/3 points
Attempts: 1 / Unlimited
1
def count_down(n):
2
”’
3
Returns the list [n, n-1, n-2, …, 1, 0]
4
5
count_down: Int -> (listof Nat)
6
7

Examples:
8
count_down(-10) => []
9
count_down(0) => [0]
10
count_down(3) => [3, 2, 1, 0]
11
”’
12
answer = []
13
while n >= 0:
14
answer.append(n)
15
n=n-1
16
return answer
17
pass
Correct! 3/3 points
From Recursion to Looping
Your code above used recursion as it is the only way (other than abstract list functions) that we know how to
iterate. In what follows, we will introduce a new technique called looping. Loops are control statements that,
similar to if statements, change the flow of your code from going top-down to possibly retracing your steps.
Take a look at the following code (documentation is above but is suppressed below for clarity). Try to guess
what happens when you run the code count_down(3). Once you’re done, run the visualizer below to
compare.
1
import check
2
3
def count_down(n):
4
answer = []
5
while n >= 0:
6
answer.append(n)
7
n
= n – 1
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch…
2/17
2022/8/21 22:27
Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online
return answer
8
9
10
11
check.expect(“Test 1”, count_down(-10), [])
12
check.expect(“Test 2”, count_down(0), [0])
13
check.expect(“Test 3”, count_down(3), [3, 2, 1, 0])
Visualize
Reset Code
Calling count_down(3) Descriptive Version
Line 3, Line 4: n = 3, answer = []
Line 5: Since n >= 0, execute Line 6, Line 7: answer = [3], n = 2
Now, return to Line 5: since n >= 0, execute Line 6, Line 7: answer = [3,2], n = 1
Now, return to Line 5: since n >= 0, execute Line 6, Line 7: answer = [3,2,1], n = 0
Now, return to Line 5: since n >= 0, execute Line 6, Line 7: answer = [3,2,1,0], n = -1
Now, return to Line 5: since n < 0, do not execute Line 6, Line 7 and skip to Line 8 Line 8: return [3,2,1,0] Concept Check 6.1.2 1/1 point (graded) Consider the following code snippet: 1 def singleton(n): 2 answer = [] 3 if n >= 0:
4
answer.append(n)
5
n = n – 1
6
return answer
What line is run after n = n – 1 is executed?
answer = []
if n >= 0
answer.append(n)
n = n – 1
return answer

https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch…
3/17
2022/8/21 22:27
Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online
Concept Check 6.1.3
1/1 point (graded)
Consider the following code snippet:
1
def singleton2(n):
2
answer = []
3
while n >= 0:
4
answer.append(n)
5
n = n – 1
6
return answer
What line is run after n = n – 1 is executed?
answer = []
while n >= 0
answer.append(n)
n = n – 1
return answer

while Loop
Suppose we have the following while loop.
1
answer = []
2
n = 5
3
while n >= 0:
4
answer.append(n)
5
n = n – 1
Below is a diagram of what we call certain components of the while loop:
1
## initialize loop variables
2
while test: # loop guard
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch…
4/17
2022/8/21 22:27
Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online
3
## body, including statements to:
4
## – update variables used in loop guard
5
## – update value being calculated
## additional processing
6
while Loop Basics
If the loop guard is True, execute the loop body.
If the loop guard is False, do not execute the loop body.
After completing the loop body, evaluate the loop guard again.
The body usually includes an update of the loop variable(s) used in the loop guard. The guarded nature of
these while loops justify why these loops are referred to as guarded iterations.
Shorthand Notation
Oftentimes in loops, a variable is either incrementing or decrementing by a fixed amount (usually 1). Python
and many other languages have a shorthand to convert n = n – 1 to n -= 1 and similarly to change n =
n + 1 to n += 1. You may use these shorthands if you so choose.
1
import check
2
3
4
def count_down(n):
5
”’
6
Returns the list [n, n-1, n-2, …, 1, 0]
7
8
count_down: Nat -> (listof Nat)
9
10
Examples:
11
count_down(-10) => []
12
count_down(0) => [0]
13
count_down(3) => [3, 2, 1, 0]
14
”’
15
answer = []
16
while n >= 0:
17
answer.append(n)
18
n
19
-= 1
return answer
20
21
check.expect(“Test 1”, count_down(-10), [])
22
check.expect(“Test 2”, count_down(0), [0])
23
check.expect(“Test 3″, count_down(3), [3, 2, 1, 0])
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch…
5/17
2022/8/21 22:27
Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online
Visualize
Reset Code
Concept Check 6.1.4
1/1 point (graded)
Consider the following code:
1
n = 5
2
total = 0
3
while n >= 0:
4
n -= 1
5
total = total + n
What is the value of total after the following is executed?
15
10
9
0
Error

Efficiency of Loops
Why use loops instead of recursion? Loops can allow for a more natural solution than recursion or abstract
list functions. The limit for how much iteration Python can do is substantially larger than how much
recursion Python can do. Looping is also far more efficient with its memory resources, as updating a
variable is much cheaper resource-wise than calling a function. Overall, iteration will run faster than
recursion.
How to Write a while Loop
To write a while loop, you must determine the following:
How to initialize variables outside the loop.
When the loop body should be executed, or when it should stop.
What variables must be updated in the loop body so the loop guard will eventually be False.
What other actions are needed within the loop body.
Example: Checking Primality
A number 𝑛 ≥ 2 is prime if it has no positive factors other than 1 and itself. The definition above gives us a
method to test if a number 𝑛 is prime:
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch…
6/17
2022/8/21 22:27
Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online
Check every number from 2 to 𝑛 − 1 . (As we saw in Module 5, we can choose to stop when
test_factor * test_factor > n)
If you find a factor of 𝑛 , stop and return False.
If none of them are, stop and return True.
See if you can determine what steps should be inside the loop, and which should be outside.
Concept Check 6.1.5
1/1 point (graded)
Recall from chapter two that an integer is said to be prime if it is an integer greater than 1 whose only
positive factors are 1 and the number itself.
Which of the following are prime numbers? Check all that apply.
Hint: These would make great test cases below!
0
1
2
3
4

Answer
Correct:
No hints for this problem!
Concept Check 6.1.6: Is Prime
Fill out the body of is_prime(n) below. A shell of a working version is given to you already.
3/3 points
Attempts: 4 / Unlimited
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch…
7/17
2022/8/21 22:27
Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online
1
def is_prime (n):
2
”’
3
Returns True if n is prime and False otherwise
4
5
is_prime: Nat -> Bool
6
”’
7
if n < 2: 8 return False#INSERT CODE HERE 9 test_factor = 2#INSERT CODE HERE 10 while test_factor < n: 11 if n % test_factor == 0: #INSERT CODE HERE (Change ***) 12 return False 13 test_factor += 1 14 15 return True ##YOUR CODE GOES HERE 16 17 ##Tried all potential factors 18  Correct! 3/3 points Testing is_prime Consider the following test cases: n=2 (loop body does not execute) n=3 (loop body executes once, terminates because test_factor equals n) n=4 (loop body executes once, terminates because 2 is a factor) n=5 (maximum iterations, no factors found) n=77 (larger composite number) n=127 (larger prime number) Each of the above represents a test case you should be considering when you write tests for your assignment code. We also note here we could mimic our improvements from module 5 here (only checking up to √𝑛 to get an even better runtime: 1 import check 2 3 4 def is_prime (n): https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch… 8/17 2022/8/21 22:27 Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online 5 ''' 6 Returns True if n is prime and False otherwise 7 8 is_prime: Nat -> Bool
9
”’
10
if n < 2: 11 return False 12 test_factor = 2 13 while test_factor * test_factor None 6 ''' 7 i = 1 8 my_list = [] 9 while i != 10: 10 my_list.append(i) 11 i = i + 2 return 12 13 14 loop_forever() Visualize Reset Code 0:00 / 0:24 https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?c… 10/17 2022/8/21 22:27 Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online 1 2 while True: print( 'runs forever' ) 1 x = -5 2 total = 0 3 while x < 0: 4 total = 2.0 ** x 5 x = x-1 6 print( total ) Visualize Reset Code The Challenge of Infinite Loops If infinite loops are so troublesome, why not write a piece of code that tests if an infinite loop is present? While this is well intended, it turns out that one can prove that, in general, you cannot write code that consumes code and that returns True if there is an infinite loop and False otherwise. Note: in certain situations, like the ones above, one could determine some common pitfalls and write code to dodge these. If this interests you, consider looking up the Halting Problem. For us, our programs have a finite time limit and will crash after that limit is exceeded. Concept Check 6.1.8 1/1 point (graded) Consider the following code: 1 ans = input("Enter Y or N: ") 2 while (ans not in ['Y','N']): 3 ans = input("Enter Y or N: ") Which of the following statements are true about the above code? The loop will always terminate. The loop will never terminate. There can be 0 iterations of the loop. Exactly two of the above. All of the above.  https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?c… 11/17 2022/8/21 22:27 Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online Concept Check 6.1.9: Factorial Up Write the body of a function factorial(n) that consumes a natural number n and returns 𝑛! . You must use a while loop in your solution and your looping variable must count from 1 to n . Do not use the math module, any recursion, or abstract list functions in your solution. 3/3 points Attempts: 1 / Unlimited 1 def factorial(n): 2 ''' 3 Returns n! 4 5 factorial: Nat -> Nat
6
7

Examples:
8
factorial(0) => 1
9
factorial(4) => 24
10
”’
11
x=1
12
while n > 0:
13
x=x*n
14
n=n-1
15
return x
16
pass
Correct! 3/3 points
Concept Check 6.1.10: Factorial Down
Write the body of a function factorial(n) that consumes a natural number n and returns 𝑛! . You must
use a while loop in your solution and your looping variable must count down from n to 1. Do not use
the math module, any recursion, or abstract list functions in your solution.
3/3 points
Attempts: 1 / Unlimited
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?c…
12/17
2022/8/21 22:27
Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online
1
def factorial(n):
2
”’
3
Returns n!
4
5
factorial: Nat -> Nat
6
7

Examples:
8
factorial(0) => 1
9
factorial(4) => 24
10
”’
11
x=1
12
while n > 0:
13
x=x*n
14
n=n-1
15
return x
16
pass
Correct! 3/3 points
Concept Check 6.1.11
Write the body of a function halve_evens_ret(L) that returns a list where all the even numbers in L
are halved. You must use while loops in your solution. Do not use recursion or abstract list functions. Do
not mutate the list.
3/3 points
Attempts: 2 / Unlimited
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?c…
13/17
2022/8/21 22:27
Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online
1
def halve_evens_ret(L):
2
”’
3
Returns a copy of L with all even numbers divided by 2
4
5
halve_evens_ret: (listof Int) -> (listof Int)
6
7
8
halve_evens_ret([]) => []
9
halve_evens_ret([1,3,5,7]) => [1,3,5,7]
10
halve_evens_ret([1,2,3,4]) => [1,1,3,2]
11
”’
12
n=0
13
los = []
14
while n < len(L): 15 if L[n] % 2 == 0: 16 los = los + [L[n] // 2] 17 n=n+1 18  Examples: else: 19 los = los + [L[n]] 20 n=n+1 21 return los 22 pass Correct! 3/3 points Concept Check 6.1.12 Write the body of a function halve_evens(L) that returns None and mutates L so that all even numbers in L are halved. You must use while loops in your solution. Do not use recursion or abstract list functions. 3/3 points Attempts: 1 / Unlimited https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?c… 14/17 2022/8/21 22:27 Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online 1 def halve_evens(L): 2 ''' 3 Returns None and mutates L so that all even numbers are halved 4 Effects: Mutates L 5 6 halve_evens: (listof Int) -> None
7
8
Examples:
9
L = []
10
halve_evens(L) => None
11
and L is still []
12
13
L = [1,3,5,7]
14
halve_evens(L) => None
15
and L is still [1,3,5,7]
16
17
L = [1,2,3,4]
18
halve_evens(L) => None
19
and L has been mutated to [1,1,3,2]
20
”’
21
n=0
22
while n < len(L): 23 if L[n] % 2 == 0: 24 L[n] = L[n] // 2 25 26  n=n+1 pass Correct! 3/3 points Concept Check 6.1.13 1/1 point (graded) Why do we use iteration via looping instead of recursion? Choose the best answer. It can allow for a more natural solution. The limit for Python to do recursion is much smaller than for looping. Loops are more efficient with memory. In general, code produced with loops is faster in Python than code done using recursion. https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?c… 15/17 2022/8/21 22:27 Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online All of the above  Concept Check 6.1.14 1/1 point (graded) Consider the following code: 1 def smaller(L,x): 2 p = 0 3 while p < len(L): 4 if L[p] < x: 5 return p 6 else: 7 p = p+1 8 return None How many times would the body of the while loop be executed if smaller([10, 8, 6],3) was called? (Count any partial executions of the body as well). 0 1 2 3 4  Concept Check 6.1.15 1/1 point (graded) Consider the following piece of code: 1 def smaller(L,x): 2 p = 0 3 while p < len(L): 4 if L[p] < x: 5 return p 6 else: 7 p = p+1 8 return None How many times would the body of the while loop be executed if smaller([7, 10, 2], 8) was https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?c… 16/17 2022/8/21 22:27 Lesson 6.1: while Loops | Lessons | CS 116 Courseware | UW Online y y p ([ ] called? (Count any partial executions of the body as well). ) 0 1 2 3 4  Final Thoughts In this lesson, we saw another way to iterate through data via while loops. This accompanies the two existing ways we have: by recursion and by abstract list functions. Key components of a while loop include the following: Initializing looping variable(s) Having a loop guard Updating the looping variable(s) in the body to make progress towards making the loop guard False Updating the answer in the loop body In the next lesson, we will visit a different kind of loop called a for loop. Using a for loop is sometimes called bounded iteration since we only loop through a list of objects. This will help us eliminate the possibility of infinite loops and can help make code easier to read. https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?c… 17/17 2022/8/21 22:28 Lesson 6.2: for Loops | Lessons | CS 116 Courseware | UW Online Lesson 6.2: for Loops Introduction: for Loops In the previous lesson, we saw a different way to do iteration, namely by looping. We discussed while loops, which are sometimes called guarded iteration because of their loop guard nature. Whenever the guard evaluates to True, we execute the body of the loop and if False, we skip the body. We saw that we could use this to loop through lists by having counters to the position. However, this feels inefficient. Could we not just loop over the elements in the list directly? It turns out we can and we can do so by using for loops in Python. Because a for loop iterates through all the elements in some fixed collection (like a string, list, or range object), we sometimes refer to for loops as bounded iteration. The following examples depict the typical behaviour of a for loop. Notice that the collection items range over can be a list, string, range, or even map/filter objects. In the case of strings, the items are individual characters. Try each of the following examples in the visualizer to help create a memory model diagram representation of how for loops work. Template: for Loops 1 ## Template to iterate over a collection via for loops 2 3 4 for item in collection: loop_body #some operations involving item Example 1: Capitalize Fruits and Vegetables 1 2 for food in ['avocado', 'banana', 'cabbage']: print(food.capitalize()) Visualize Reset Code Example 2: Printing DNA 1 2 for base in 'ACGGGTCG': print(base) https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch… 1/13 2022/8/21 22:28 print(base) 2 Visualize Lesson 6.2: for Loops | Lessons | CS 116 Courseware | UW Online Reset Code Example 3: Sum of Squares 1 import check 2 3 4 def sum_squares(a, b): 5 ''' 6 Returns the sum of squares from a to b inclusive. 7 sum_squares: Nat Nat -> Nat
8
9
Examples:
10
11
sum_squares(2, 1) => 0
12
sum_squares(1, 2) => 5
13
”’
14
sum_all = 0
15
for i in range(a,b + 1):
16
sq = i*i
17
sum_all = sum_all + sq
return sum_all
18
19
20
21
check.expect(“Test 1”, sum_squares(2,1), 0)
22
check.expect(“Test 2”, sum_squares(1,2), 5)
23
check.expect(“Test 3”, sum_squares(2,5), 54)
Visualize
Reset Code
Example 4: Counting by 2s
1
2
for j in range(-10,2,2):
print(j)
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch…
2/13
2022/8/21 22:28
Lesson 6.2: for Loops | Lessons | CS 116 Courseware | UW Online
Visualize
Reset Code
The next video contains 2 questions.
If you are having problems viewing the in video questions, please try the following:
Make sure you are using a course approved browser
Do not watch the videos at more than 1.0x speed
Do not watch the videos in full screen.
Do not scrub the videos (fast forward/rewind to find the videos).
Try clearing your cache and rewatching the video.
There are not many videos in this course so we do expect you to take the time to actually watch them in
their entirety.
Compare and Contrast while and for Loops
Function
while Loop
for Loop
Initialization
Loop counter should be initialized
outside loop
Loop counter initialized automatically
Continuation
Includes continuation test before body
Continues while more elements in the
collection
Updates
Should update loop variables in body of
loop
Loop variable updated automatically
Does not update in loop
Repetition
Body contains steps to repeat
Body contains steps to repeat
Concept Check 6.2.1
1/1 point (graded)
Consider the following code:
1
def f(n):
2
total = 0
3
for k in range(n):
4
total = total + k
5
return total
What is the value of f(5)?
0
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch…
3/13
2022/8/21 22:28
Lesson 6.2: for Loops | Lessons | CS 116 Courseware | UW Online
5
10
15
There is an error in the code

Concept Check 6.2.2
1/1 point (graded)
Consider the following code:
def f(n):
1
2
total = 0
3
for k in range(n):
4
total = total + k
return total
5
What is the value of f(5)?
0
5
10
15
There is an error in the code

Concept Check 6.2.3
1/1 point (graded)
Consider the following code:
1
L = [“apple”, “banana”, “cabbage”]
2
for item in L:
3
item = “daikon”
What is the value of L after the above is executed?
[“apple”, “banana”, “cabbage”]
[“daikon”, “banana”, “cabbage”]
[“daikon”, “daikon”, “daikon”]
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch…
4/13
2022/8/21 22:28
Lesson 6.2: for Loops | Lessons | CS 116 Courseware | UW Online
There is an error in the above code
None of the above

Mutating Elements via a for Loop
It is important to note that the previous example does not give a valid way to mutate a list with a for loop.
Like with recursion, we actually want to loop through the list by position rather than by going through each
element individually. We can do this by using the range command on the length of the list.
Please note this is extremely important! You cannot use the template
1
for item in collection:
2
item = “something”
and mutate the elements of collection (this was the learning moment in the previous
concept check)! In fact, anything you can do with the above syntax you can do with the syntax
below which loops over indices of a list but the converse is not true! That is, there are things
you can do if you loop over the list by its position that you cannot do if you use the above
collection looping syntax (think back to how this was also true with recursion). Most
programming languages force you to loop over the indices in a collection as is done below
however Python is generous and supports many different syntax uses which can cause
confusion if you are not careful.
1
## Template for List Mutation via for loops
2
3
def mutation_template_for_loop(L):
4
for pos in range(len(L)):
5
L[pos] = ##something
Concept Check 6.2.4
1/1 point (graded)
Consider the following code:
1
L = [“apple”, “banana”, “cabbage”]
2
for pos in range(len(L)):
3
L[pos] = “durian”
What is the value of L after the above is executed?
[“apple”, “banana”, “cabbage”]
[“durian”, “banana”, “cabbage”]
[“durian”, “durian”, “durian”]
There is an error in the above code
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch…
5/13
2022/8/21 22:28
Lesson 6.2: for Loops | Lessons | CS 116 Courseware | UW Online
None of the above

Concept Check 6.2.5: multiply_by Revisited
Recall the multiply_by example from a previous module.
The function multiply_by consumes a list of integers (called values ) and an integer (called factor )
and mutates values by multiplying each entry in values by factor. The function returns None .
Implement the body of multiply_by using a for loop.
3/3 points
Attempts: 1 / Unlimited
1
def multiply_by(values, factor):
2
”’
3
Returns None and mutates values so that each entry
4
is multiplied by factor
5
6
Effects: Mutates values
7
8
multiply_by: (listof Int) Int -> None
9
10
Examples:
11
L = []
12
multiply_by(L, 14) => None
13
and L is still []
14
15
L = [1, 2, 3]
16
multiply_by(L, 4) => None
17
and L is [4, 8, 12]
18
19
L = [1, 22]
20
multiply_by(L, 0) => None
21
and L is [0, 0]
22
”’
23
for n in range(len(values)):
24

values[n] = values[n] * factor
Correct! 3/3 points
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch…
6/13
2022/8/21 22:28
Lesson 6.2: for Loops | Lessons | CS 116 Courseware | UW Online
Concept Check 6.2.6
1/1 point (graded)
Consider the following code:
1
2
def smaller(L,x):
for p in range(len(L)):
3
if L[p] < x: 4 return p 5 return None How many times would the body of the for loop be executed if smaller([10,8,6],3) was called? 0 1 2 3 4  Concept Check 6.2.7 1/1 point (graded) Consider the following code: 1 2 def smaller(L,x): for p in range(len(L)): 3 if L[p] < x: 4 return p 5 return None How many times would the body of the for loop be executed if smaller([7,10,2],8) was called? 0 1 2 3 4  https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch… 7/13 2022/8/21 22:28 Lesson 6.2: for Loops | Lessons | CS 116 Courseware | UW Online Prohibited Commands: Continue and Break It is possible you have read about the commands continue and break. While Python does support these commands, in this course, you will be forbidden from using them. These commands often make code harder to read and are not necessary to make code do what you want it to do. Concept Check 6.2.8: Warning 1/1 point (graded) Consider the following code: 1 L = [2, 4, 6, 8, 10] 2 for x in L: 3 if x % 2 == 0: 4 L.remove(x) What is the value of L after the above is executed? [] [2, 6, 10] [4, 8] [2, 4, 6, 8, 10] None of the above  Concept Check Feedback Test out the above code in the visualizer! The answer is actually correct. The moral of the above is that you should avoid iterating directly over a list you are mutating. A while loop works much better when attempting to accomplish this task in Python. You can also make a copy of the collection and then loop over the copy so that you are not modifying a looping collection while looping over it. In the end, just be careful if doing this. Concept Check 6.2.9 Write the body of a function all_same_type(L) that consumes a list of any type and returns true if and only if each element in the list has the same type. You must use for loops in your solution. Do not use while loops, recursion, or abstract list functions. Do not mutate the list. Note: The type command does not distinguish between types of lists. For example, type([1,2]) == type(['a','b']) For this problem, assume any type of list is the same type [of list]. 3/3 points Attempts: 1 / Unlimited https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch… 8/13 2022/8/21 22:28 Lesson 6.2: for Loops | Lessons | CS 116 Courseware | UW Online 1 def all_same_type(L): 2 ''' 3 Returns True if and only if each element of L has the same type 4 and False otherwise. 5 6 all_same_type: (listof Any) -> Bool
7
8
9
all_same_type([]) => True
10
all_same_type([2, 5, 3]) => True
11
all_same_type([2, ‘R’, 4.56]) => False
12
”’
13
for n in range(len(L)):
14
15
16
17

Examples:
if n > 0:
if type(L[n]) != type(L[n – 1]):
return False
return True
Correct! 3/3 points
Concept Check 6.2.10
Write the body of a function halve_evens_ret(L) that returns a list where all the even numbers in L
are halved. You must use for loops in your solution. Do not use while loops, recursion, or abstract list
functions. Do not mutate the list.
3/3 points
Attempts: 1 / Unlimited
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?ch…
9/13
2022/8/21 22:28
Lesson 6.2: for Loops | Lessons | CS 116 Courseware | UW Online
1
def halve_evens_ret(L):
2
”’
3
Returns a copy of L with all even numbers divided by 2
4
5
halve_evens_ret: (listof Int) -> (listof Int)
6
7
8
halve_evens_ret([]) => []
9
halve_evens_ret([1,3,5,7]) => [1,3,5,7]
10
halve_evens_ret([1,2,3,4]) => [1,1,3,2]
11
”’
12
answer = []
13
for n in range(len(L)):
14
if L[n] % 2 == 0:
15
16
17

Examples:
answer = answer + [L[n] // 2]
else:
answer = answer + [L[n]]
18
return answer
19
pass
Correct! 3/3 points
Concept Check 6.2.11
Write the body of a function halve_evens(L) that returns None and mutates L so that all even
numbers in L are halved. You must use for loops in your solution. Do not use while loops, recursion,
or abstract list functions.
3/3 points
Attempts: 1 / Unlimited
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?c…
10/13
2022/8/21 22:28
Lesson 6.2: for Loops | Lessons | CS 116 Courseware | UW Online
1
def halve_evens(L):
2
”’
3
Returns None and mutates L so that all even numbers are halved
4
5
Effects: Mutates L
6
7
halve_evens: (listof Int) -> None
8
9
Examples:
10
L = []
11
halve_evens(L) => None
12
and L is still []
13
14
L = [1,3,5,7]
15
halve_evens(L) => None
16
and L is still [1,3,5,7]
17
18
L = [1,2,3,4]
19
halve_evens(L) => None
20
and L has been mutated to [1,1,3,2]
21
”’
22
for n in range(len(L)):
23
if L[n] % 2 == 0:
24
L[n] = L[n] // 2
25
pass
Correct! 3/3 points

Concept Check 6.2.12: Another Warning
1/1 point (graded)
Consider the following code:
1
import check
2
3
def foo():
4
inp = input()
5
for i in range(4):
6
print(inp)
Which of the following is a valid test for the above code? Check all that apply.
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?c…
11/13
2022/8/21 22:28
Lesson 6.2: for Loops | Lessons | CS 116 Courseware | UW Online
1
check.set_input(1)
2
check.set_print_exact(1, 1, 1, 1)
3
check.expect(‘Simple Test’, foo(), None)
1
check.set_input(‘1’)
2
check.set_print_exact(‘1’, ‘1’, ‘1’, ‘1’)
3
check.expect(‘Simple Test’, foo(), None)
1
check.set_input(1, 2, 3, 4)
2
check.set_print_exact(1, 2, 3, 4)
3
check.expect(‘Simple Test’, foo(), None)
1
check.set_input(‘1’, ‘2’, ‘3’, ‘4’)
2
check.set_print_exact(‘1’, ‘2’, ‘3’, ‘4’)
3
check.expect(‘Simple Test’, foo(), None)
1
check.set_input(‘1’, ‘2’, ‘3’, ‘4’)
2
check.set_print_exact(‘1’, ‘1’, ‘1’, ‘1’)
3
check.expect(‘Simple Test’, foo(), None)

Concept Check 6.2.13
1/1 point (graded)
Consider the following code:
1
for i in 5:
2
print(i)
The above gives an error message ‘int’ object is not iterable. Which of the following best explains why?
There is an indentation error.
The print statement has a syntax error.
The for loop variable i needs to iterate over something iterable like a list of range object.
The code for i in is incorrect.

Final Thoughts
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?c…
12/13
2022/8/21 22:28
Lesson 6.2: for Loops | Lessons | CS 116 Courseware | UW Online
In this lesson, we discussed bounded iteration via for loops. Combined with while loops, we can see that
looping can give us another powerful way to iterate through data. Be careful when mutating a list you are
looping over with a for loop. Also, be careful about where your return statements are placed. Lastly,
remember just like with recursion, if using a for loop to mutate a list, be sure to loop by position. In the
next lesson, we will go through a few examples of looping involving nested lists.
https://online.cs.uwaterloo.ca/courses/course-v1:UW+CS116+2022_05/courseware/5c74ab207b6f4bedbd7e7feb4003cf2c/9a75cb1423674e30835cd59f7216ef9b/?c…
13/13

Save Time On Research and Writing
Hire a Pro to Write You a 100% Plagiarism-Free Paper.
Get My Paper
Still stressed from student homework?
Get quality assistance from academic writers!

Order your essay today and save 25% with the discount code LAVENDER