Today I am looking at an example of the divide and conquer method. The code is as follows:
def get_max(max_list):
return max(max_list)
def solve(init_list):
n = len(init_list)
if n <= 2:
return get_max(init_list)
temp_list = (init_list[i:i+2] for i in range(0, n, 2))
# print 'temp_list: ' + str(temp_list)
print temp_list
max_list = list(map(get_max, temp_list))
return solve(max_list)
There are two questions:
1.temp_list生成的是tuple類型嗎?我打印出來的結(jié)果是<generator object <genexpr> at 0x00000000023570D8>, 為什么是這樣?
2. list(map(get_max, temp_list))是把map類型轉(zhuǎn)成了list, 但是這里為什么要用map呢?
if __name__ == "__main__":
test_list = [12, 2, 23, 45, 67, 3, 2, 4, 45, 63, 24, 23]
print solve(test_list)
1、init_list傳入的時候就是generator
2、list(map(get_max, temp_list)相當(dāng)于[get_max(t) for t in temp_list]
You can refer to this wiki page.
is not map
類型轉(zhuǎn)成了list
,map
不是類型,而是一個內(nèi)置函數(shù),他的作用是對temp_list
里面的每個元素apply到get_max
這個函數(shù)里面,最后再把結(jié)果轉(zhuǎn)變成list
. You can take a look at the documentation. It is recommended that the questioner read the basics of python.