【问题标题】:Python filter(predicate, current, threshold)Python 过滤器(谓词、电流、阈值)
【发布时间】: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


【解决方案1】:
def filter(predicate, current, threshold):
    if current > threshold:
        return ''
    else:
        return (str(current) + " " if predicate(current) else '') + filter(predicate, current + 1, threshold)

threshold = 20
predicate1 = lambda x: x % 2 == 0
predicate2 = lambda x: x % 3 == 0
res = filter(predicate1, 1, threshold)
print(res)

当您有 lambda 或返回“x == y”的函数或任何其他运算符时 - 将返回一个布尔值。

而且每次调用函数时都必须给当前变量加1,否则会得到无限循环函数。

【讨论】:

    猜你喜欢
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多