我最近在学习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
虽然我解决了这个问题,但是是不停的尝试编码得出来的。
还是想知道原理和思路
函数组成了一个链,链的末尾是checker函数。
链的头部是inner,环境为i=n,fn=inner
x % i == 0 为True的时候 return True
为False的时候调用fn(x).
直到checker函数返回False.