【发布时间】:2020-10-07 11:00:24
【问题描述】:
我正在做一个关于 lambdas 的学校练习,你必须在其中填写代码才能使程序运行。我可以看到结果是什么,但我无法将我的想法转换为代码。你能帮忙吗?
这是练习:
FILTER 将一个函数(谓词)和两个数字(电流和阈值)作为输入。它递归地创建一个字符串,其中仅当将谓词应用于此类数字的结果为真时才保留数字(从当前到阈值)。
predicate1 检查输入是否可被 2 整除
predicate2 检查输入是否可被 3 整除
Test1:使用谓词1
Test2:使用谓词2
这是代码:下划线是我可以放代码的地方:
def filter(predicate, current, threshold):
if ________ > _________
return ''
else:
_______________________
_______________________
threshold = 20
predicate1 = lambda x: x % 2 == 0
predicate2 = lambda x: x % 3 == 0
res = filter(predicate1, 1, threshold)
print()
我在下面想出了这个,但它不起作用:
def filter(predicate, current, threshold):
if current > threshold:
return ''
else:
new_result = filter(predicate, predicate(current), threshold)
result = str(predicate(current)) + ' ' + new_result
return result
threshold = 20
predicate1 = lambda x: x % 2 == 0
predicate2 = lambda x: x % 3 == 0
res = filter(predicate1, 1, threshold)
print()
有什么建议吗?
【问题讨论】:
-
你应该试着了解
predicate返回什么样的值,current应该是什么样的值。
标签: python lambda filter predicate threshold