首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python多功能组合

Python多功能组合
EN

Stack Overflow用户
提问于 2019-03-23 03:29:03
回答 2查看 249关注 0票数 0

所以我有一个家庭作业问题,但我不知道为什么我搞错了/它是如何工作的。

代码语言:javascript
运行
复制
once = lambda f: lambda x: f(x)
twice = lambda f: lambda x: f(f(x))
thrice = lambda f: lambda x: f(f(f(x))) 
print(thrice(twice)(once)(lambda x: x + 2)(9))

我的ans: 25 -> 8*2 +9

实际ans: 11 -> 2+9

我当时在想:

(三次-> f(X)),设new_x =2(X)

三次-> f(f(new_x)),设new_x2 =2次(New_x)

三次-> f(new_x2),设new_thrice =2次(New_x2)

因此,之后我添加了(once),并执行了new_thrice(once)(lambda x: x+2)(9)

但答案似乎是,(once)取消了早期的thrice(twice),并且迷失了方向。如果有人有解释的话那就太好了。谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-23 06:44:38

once(lambda x: x+2)的计算结果是将lambda x: x+2应用于其参数的函数。换句话说,它等同于lambda x: x+2

once(once(lambda x: x+2))的计算结果是将once(lambda x: x+2)应用于其参数的函数。换句话说,它也等同于lambda x: x+2

once(once(once(lambda x: x+2)))的计算结果是将once(once(lambda x: x+2))应用于其参数的函数。换句话说,这也等同于lambda x: x+2。无论您应用once多少次,这种情况都不会改变。

thrice(twice)(once)计算为一个函数,该函数多次将once应用于其参数。(8次,这对分析并不重要) once不会改变函数的行为。不管您应用了多少次once,最后一个函数只应用底层函数一次。

因此,thrice(twice)(once)(lambda x: x + 2)的计算结果是执行与lambda x: x + 2相同的操作的函数。

现在,如果是thrice(twice)(once(lambda x: x + 2)) (请注意移动的括号),那么这将将thrice(twice)应用于once(lambda x: x + 2),其结果将是一个应用lambda x: x + 2 8次的函数。

票数 -1
EN

Stack Overflow用户

发布于 2019-03-23 04:21:19

我希望这能帮你弄清楚到底是怎么回事!

代码语言:javascript
运行
复制
once = lambda f: lambda x: f(x)
twice = lambda f: lambda x: f(f(x))
thrice = lambda f: lambda x: f(f(f(x)))

# Created this one to help readability.
custom_func = lambda x: x + 2

print("once:", once(custom_func)(9))  # returns value
print("twice:", twice(custom_func)(9))  # returns value
print("thrice:", thrice(custom_func)(9))  # returns value

print("applying all those:", thrice(custom_func)(twice(custom_func)(once(custom_func)(9))))
# This represents the following: (((9 + 2) + 2 + 2) + 2 + 2 + 2)
# each pair of parenthesis mean one function being applied, first once, then twice, then thrice.

# If I've understood correctly you need to achieve 25
# to achieve 25 we need to apply +4 in this result so, which means +2 +2, twice function...
print("Achieving 25:", twice(custom_func)(thrice(custom_func)(twice(custom_func)(once(custom_func)(9)))))

# That is it! Hope it helps.
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55310356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档