python 高阶函数

我最近在学习python,在做练习题的时候被卡住了。
题目要求是按照框架填空
div_by_primes_under_no_lambda(n)返回一个函数
div_by_primes_under_no_lambda(n)(x) 返回一个布尔值。2 - n中有没有数可以整除x

def div_by_primes_under_no_lambda(n):
"""
>>> div_by_primes_under_no_lambda(10)(11)
False
>>> div_by_primes_under_no_lambda(10)(121)
False
>>> div_by_primes_under_no_lambda(10)(12)
True
>>> div_by_primes_under_no_lambda(5)(1)
False
"""
def checker(x):
return False
i = ____________________________
while ____________________________:
if not checker(i):
def outer(____________________________):
def inner(____________________________):
return ____________________________
return ____________________________
checker = ____________________________
i = ____________________________
return ____________________________
def div_by_primes_under_no_lambda(n):
"""
>>> div_by_primes_under_no_lambda(10)(11)
False
>>> div_by_primes_under_no_lambda(10)(121)
False
>>> div_by_primes_under_no_lambda(10)(12)
True
>>> div_by_primes_under_no_lambda(5)(1)
False
"""
def checker(x):
return False
i = 2
while i <= n:
if not checker(i):
def outer(i):
def inner(x):
return True if (x % i == 0 and i >= 2) else False if i < 2 else outer(i - 1)(x)
return inner
checker = outer(n)
i = n + 1
return checker

我的解法虽然通过了文档测试,但是这个while循环就是多余的。
请教下这个练习的解题思路,应该如何去思考这类问题。

回答

def div_by_primes_under_no_lambda(n):
    """
    >>> div_by_primes_under_no_lambda(10)(11)
    False
    >>> div_by_primes_under_no_lambda(10)(121)
    False
    >>> div_by_primes_under_no_lambda(10)(12)
    True
    >>> div_by_primes_under_no_lambda(5)(1)
    False
    """

    def checker(x):
        return False

    i = 2
    while i <= n:
        if not checker(i):
            def outer(fn, i):
                def inner(x):
                    return x % i == 0 else fn(x)

                return inner

            checker = outer(checker, i)
        i = i + 1
    return checker
以上是python 高阶函数的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>