簡體   English   中英

Python多功能組合

[英]Python Multiple Function Composition

所以我有一個作業問題,但是我不確定為什么弄錯了/如何工作。

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(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)無效並迷失了。 有人解釋會很棒..謝謝!

希望這可以幫助您弄清楚發生了什么!

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.

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的函數lambda x: x + 2 8次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM