Try   HackMD

Drill 11 Solution

Question 1

Fill in the function to compute the product of elements in a list of integers:

def product(lst : <blank 1>) -> <blank 2>:
  <blank 3> = <blank 4>
  for <blank 5>:
    result = result + num
  <blank 6>
Answer

Blank 1: list

Blank 2: int

Blank 3: result

Blank 4: 1

Blank 5: num in lst

Blank 6: return result

Question 2

What does this function return when [1, 2, 3] is passed in?

To indicate a list, use the notation above, with brackets, commas, and each element separated by a space.

To indicate an error, type "ERROR" (without quotes).

def mystery(l : list):
    for i in l:
        return i
Answer

1

This function will return the first element of the list in the first iteration of the for loop.

Question 3

What does this function return when [1, 2, 3] is passed in?

To indicate a list, use the notation above, with brackets, commas, and each element separated by a space.

To indicate an error, type "ERROR" (without quotes).

def mystery(l : list):
    result = 0
    for i in l:
        result = i
    return result
Answer

3

In each iteration of the loop, result will be updated with the current value of i. In the last iteration of the loop, result will be updated with 3 and then returned from the function after the loop.

Question 4

What does this function return when [] is passed in? This is the same function as the last question.

To indicate a list, use the notation in the previous questions, with brackets, commas, and each element separated by a space.

To indicate an error, type "ERROR" (without quotes).

def mystery(l : list):
    result = 0
    for i in l:
        result = i
    return result
Answer

0

result will never be updated before it's returned from the function.

Question 5

What does this function return when [1, 2, 3] is passed in?

To indicate a list, use the notation above, with brackets, commas, and each element separated by a space.

To indicate an error, type "ERROR" (without quotes).

def mystery(l : list):
    result = 0
    for i in l:
        if i == 0:
            return False
    return True
Answer

True

False won't be returned for any of the loop values (because none of the loop values are 0). True will then be returned after the loop.

Question 6

True/False: If we wanted to write a function to return the third element of a list, a for-loop would be the right approach.

Answer

False: If we have a list li, we can access the third element with li[2].

Question 7

True/False: If we wanted to write a function to count the number of times the list's third element was repeated in the list, a for-loop would be the right approach.

Answer

True