Problem 2: Count van Count (100pts)
Problem
Consider the following implementations of
count_factorsandcount_primes:
考虑以下 count_factors 和 count_primes 的实现:
def count_factors(n):
"""Return the number of positive factors that n has.
>>> count_factors(6)
4 # 1, 2, 3, 6
>>> count_factors(4)
3 # 1, 2, 4
"""
i, count = 1, 0
while i <= n:
if n % i == 0:
count += 1
i += 1
return count
def count_primes(n):
"""Return the number of prime numbers up to and including n.
>>> count_primes(6)
3 # 2, 3, 5
>>> count_primes(13)
6 # 2, 3, 5, 7, 11, 13
"""
i, count = 1, 0
while i <= n:
if is_prime(i):
count += 1
i += 1
return count
def is_prime(n):
return count_factors(n) == 2 # only factors are 1 and n
The implementations look quite similar! Generalize this logic by writing a function
count_cond, which takes in a two-argument predicate functioncondition(n, i).count_condreturns a one-argument function that takes inn, which counts all the numbers from1tonthat satisfyconditionwhen called.
这些实现看起来非常相似!通过编写一个函数 count_cond 来概括这个逻辑,该函数接受一个双参数谓词函数 condition(n, i)。count_cond 返回一个单参数函数,该单参数函数接受 n,并计算从 1 到 n 之间所有满足调用 condition 时的条件的数字个数。
def count_cond(condition):
"""Returns a function with one parameter N that counts all the numbers from
1 to N that satisfy the two-argument predicate function Condition, where
the first argument for Condition is N and the second argument is the
number from 1 to N.
>>> count_factors = count_cond(lambda n, i: n % i == 0)
>>> count_factors(2) # 1, 2
2
>>> count_factors(4) # 1, 2, 4
3
>>> count_factors(12) # 1, 2, 3, 4, 6, 12
6
>>> is_prime = lambda n, i: count_factors(i) == 2
>>> count_primes = count_cond(is_prime)
>>> count_primes(2) # 2
1
>>> count_primes(3) # 2, 3
2
>>> count_primes(4) # 2, 3
2
>>> count_primes(5) # 2, 3, 5
3
>>> count_primes(20) # 2, 3, 5, 7, 11, 13, 17, 19
8
"""
"*** YOUR CODE HERE ***"
Hints
- 考虑编写一个从1到n的循环,对每一个数字判断是否满足条件
Solutions
使用 while 循环:
def count_cond(condition):
def count(n):
result, i = 0, 1
while i <= n:
if condition(n, i):
result += 1
i += 1
return result
return count
使用 for 循环:
def count_cond(condition):
def count(n):
result = 0
for i in range(1, n + 1):
if (condition(n, i)):
result += 1
return result
return count