Sitemap
John

John

NUS Singapore, from Taiwan, https://github.com/YCtw

Python — High Order Functions

10 min readOct 12, 2022

--

High Order Functions的定義,只要符合兩者其一:

  • 接收其他Function做為參數運算
  • 回傳物件為一個Function(eg. Decorator)

這篇文章專注在第一點的High Order Functions運用,第二點會額外的寫另一篇關於Closure和Decorator的文章。

所記錄的High Order Functions主要都是結合Function和Iterable的運用,讓整體程式時更有效率,也提供面對相關問題的一個解法。

文章簡介

  • sorted
  • map
  • filter
  • reduce
  • partial

sorted

sorted(iterable, key=None, reverse=False) -> return an list

這之中最常用到的function,可以sort任何型態的Iterable,按照傳入的key function規則去sort,reverse=False表示由小排到大,反之。

Ex1: sort [-1,-3,4,5,-6,8,-2] base on their power of square value, in descending order.

list_a = [-1,-3,4,5,-6,8,-2]sorted_list_a = sorted(list_a, key=lambda x:x**2, reverse=True)print(sorted_list_a) #[8, -6, 5, 4, -3, -2, -1]

Ex2: sort {‘a’: 42, ‘b’: 3, ‘c’: 92,’ d’: 88, ’e’: 15, ‘f’: 9, ‘g’: 35} base on their value, in ascending order.

dict_a =  {‘a’: 42, ‘b’: 3, ‘c’: 92,’ d’: 88, ’e’: 15, ‘f’: 9, ‘g’: 35}sorted_key = sorted(dict_a, key=lambda x:dict_a[x], reverse=False)print(sorted_key) #['b', 'f', 'e', 'g', 'a', ' d', 'c']

map

map(func, iterable) -> return lazy iterator

回傳的結果是一個Lazy Iterator,內含傳入的Iterable元素經過傳入function的運算結果,關於Iterator和Iterable,可以參考Python — Iterator & Iterable(Basic)。

map的使用情境是應用傳入的function到所有傳入的Iterable元素上,不過主要我還是會習慣直接寫comprehension多點。

Ex1: Apply power function to Iterable

list_a = [1,2,3,4]
def power(x):
return x**2
result = map(power, list_a)
print(list(result)) #[1,4,9,16]

Ex2: More than 1 Iterable passed in(可以傳不只一個Iterable)

list_a = [1,2,3,4]
list_b = [10,20,30,40]
result = map(lambda x,y: x+y, list_a, list_b)
print(list(result)) #[11,22,33,44]

filter

filter(func, iterable) -> return lazy iterator

會讓傳入的iterable去跑傳入的function,最終結果truth value為True的元素會被留下。如果沒有傳入的function的話,則單純檢查Iterable元素的truth value。

Ex: Filter out the multiples of 2

list_a = [1,2,3,4,5,6]result = filter(lambda x: x%2==0, list_a)
print(list(result)) #[2,4,6]

reduce

reduce(func, iterable, initial=None) -> return a single value

Python reducing function又稱accumulators、aggregators或是folding functions,像是常見的max()、min()都是這個概念。

我通常稱這個function為收斂function,因為這個function在做的就是透過不斷的把Iterable裡的元素一個一個拿出來做運算,最終收斂出一個結果。

Get John’s stories in your inbox

Join Medium for free to get updates from this writer.

Ex1: find the max value of [3,5,6,2]

  • Without using reduce function:沒有reduce function的情況下,我們會怎麼做,我們會先把Iterable中的第一個element當做max value,接著從第二element開始做for loop與max value做比較,若element比較大則讓其成為max value,最終跑完會得到整個Iterable的max value。
list_a = [3,5,6,2]#Get the bigger valu
bigger_value = lambda x, y: x if y>x else y
def max_sequence(target_list):
max = target_list[0]
for number in target_list[1:]:
#constantly compare max with element in iterable
max = bigger_value(max, number)
return max
print(max_sequence(list_a)) #6
  • With reduce function:我們需要設計一個傳入的function,這個function接收兩個參數,第一個用來記錄每次做完比較後的max_value,第二個用來接收不斷迭代進來的Iterable element。
from functools import reduce #需要先從functoolos module導入max_value = reduce(lambda x, y: x if x>y else y, list_a)
print(max_value) #6

這段程式重點是傳入的lambda function,x會紀錄上次跑完後面比較的結果,y是list_a迭代進來的element。reduce function會自動幫你做到紀錄與迭代運算這兩件事情

Press enter or click to view image in full size
reduce function運算

Ex2: Calculating the sum of [3,5,6,2,9,13,7,12]

  • Without reduce function: 和上面找max value是同個概念,只是這次我們會先把需要一個accumulate value來記錄每次加總後的結果。
list_a =  [3,5,6,2,9,13,7,12]
adding = lambda x, y:x+y
def add_sequence(target_list):
add_result = target_list[0]
for number in target_list[1:]:
add_result = adding(add_result, number)
return add_result
print(add_sequence(list_a)) #57
  • With reduce function
list_a = [3,5,6,2,9,13,7,12]
add_result = reduce(lambda x,y: x+y, list_a)
print(add_result)) #57

上述的兩個例子,Python都已經有built-in functions可以實現以上的功能,除此之外還有其他像是max()、min()、sum()…etc

設定initial

reduce function還有一個optional的參數是initial,決定了最一開始那次的迴圈x的值,換言之x不一定要從第一個element開始,可以自己設定一個開頭的元素,傳入的Iterable則從第一個y開始被傳入運算。

Ex1: find the max value of [3,5,6,2] with reducing function, initial as 9

list_a = [3,5,6,2]#9 as initial
max_value = reduce(lambda x, y: x if x>y else y, list_a, 9)

print(max_value) #9
Press enter or click to view image in full size
reduce function with initial value

partial

partial(func, arguments) -> return a function

partial做的事情是包裝一個function,並且在包裝的過程同時設定原function的參數,最後回傳新function,新function要回傳的參數就會比較少。

以下看個partial的使用:

from functools import partial#寫一個function去計算傳入底數的次方
def exponent(base, power):
return base ** power
#預先填好power=2,讓這個function成為計算平方的function
square = partial(exponent, power=2)
#預先填好power=3,讓這個function成為計算平方的function
cube = partial(exponent, power=3)
#只要傳base就好
print(square(2)) #4
print(cube(2)) #8

這就是簡化function傳參數的過程。partial的使用情境比較特別,遇到如果程式運算過程傳參數有限制時能更體驗這個function有用之處。

如果今天我們遇到一個function只能接受一個參數傳入:

Ex: sort the dot list base on dot’s distance from origin(0,0)

origin = (0,0)
dot_list = [(0,2),(3,2),(-1,-3),(5,4)]
#寫一個function去計算兩點的距離
distance = lambda x,y: ((x[0]-y[0])**2) + ((x[1]-y[1])**2)
#predifine y=origin
partial_distance = partial(distance, y=origin)
#sorted
sorted_dot_list = sorted(dot_list, key=partial_distance)
print(sorted_dot_list) #[(0, 2), (-1, -3), (3, 2), (5, 4)]

以上例子可以看到主要解決的問題點是sorted function每次只會從傳入的iterable中拿出一個元素並傳入key中,但原本的distance function會需要兩個參數,因此我們使用partial function去包裝原先的distance function,把y先傳好origin(0,0),因此在sorted時,key只需要將接收到的迭代元素對上剩下的一個參數就好。

--

--