Python多功能组合

时间:2019-03-23 03:29:04

标签: python

所以我有一个作业问题,但是我不确定为什么我弄错了/它如何工作。

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))

我的回答:25-> 8 * 2 +9

实际回答:11-> 2 + 9

我在想什么:

三次-> f(f(f(x()))), 让new_x =两次(x)

三次-> f(f(new_x)), 让new_x2 =两次(new_x)

三次-> f(new_x2), 让new_thrice =两次(new_x2)

所以后来我添加了(once)并做了 new_thrice(once)(lambda x: x+2)(9)

但是答案似乎是(once)使较早的thrice(twice)无效并且迷路了。有人解释会很好。谢谢!

2 个答案:

答案 0 :(得分:0)

我希望这会帮助您弄清楚发生了什么事!

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 :(得分:-1)

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次。