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类型吗?我打印出来的结果是<generator object <genexpr> at 0x00000000023570D8>, 为什么是这样?
2. list(map(get_max, temp_list))是把map类型转成了list, 但是这里为什么要用map呢?
if __name__ == "__main__":
test_list = [12, 2, 23, 45, 67, 3, 2, 4, 45, 63, 24, 23]
print solve(test_list)
You can refer to this wiki page.
is not
map
类型转成了list
,map
不是类型,而是一个内置函数,他的作用是对temp_list
里面的每个元素apply到get_max
这个函数里面,最后再把结果转变成list
. You can take a look at the documentation. It is recommended that the questioner read the basics of python.