所以我有一个家庭作业问题,但我不知道为什么我搞错了/它是如何工作的。
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)
,并且迷失了方向。如果有人有解释的话那就太好了。谢谢!
发布于 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次的函数。
发布于 2019-03-23 04:21:19
我希望这能帮你弄清楚到底是怎么回事!
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.
https://stackoverflow.com/questions/55310356
复制相似问题