Lab05 solutions (UCB CS61A@2021 Fall)
Lists
Q1: Factors List
Write
factors_list, which takes a numbernand returns a list of its factors in ascending order.
We can know such a basic mathematical fact: the factor of a number can only be up to half of it (when the number is even). So we use for i in range(1, n // 2 + 1)
def factors_list(n):
"""Return a list containing all the numbers that divide `n` evenly, except
for the number itself. Make sure the list is in ascending order.
>>> factors_list(6)
[1, 2, 3]
>>> factors_list(8)
[1, 2, 4]
>>> factors_list(28)
[1, 2, 4, 7, 14]
"""
all_factors = []
# the biggest number which can divide `n` evenly will be `n // 2`
for i in range(1, n // 2 + 1):
if n % i == 0:
all_factors.append(i)
return all_factors
Q2: Flatten
Write a function
flattenthat takes a list and “flattens” it. The list could be a deep list, meaning that there could be a multiple layers of nesting within the list.