Question: Write a function which counts the numbers from 1 to n that meet any given condition. This function, count_cond , takes in a two-argument predicate
Write a function which counts the numbers from 1 to n that meet any given condition. This function, count_cond, takes in a two-argument predicate function condition(n, i) as an argument. count_cond then returns a one-argument function that takes in n. The function counts all the numbers from 1 to n that satisfy condition when called (see examples in the docstring below). Your function should look similar to count_primes and count_factors given above.
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 ***"
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
