我正在尝试编写一个递归函数,以便在列表列表中找到最大整数。我知道如何为整数列表编写函数。谁能给我一些提示?我 我正在考虑在没有 Max 功能的情况下这样做。 前任。 a = [1, [2,3], 4, [[2], 1]] find_max(a) ->4
最佳答案
我决定用纯递归来解决这个问题,没有循环。以下似乎对我有用:
def find_max(a_list):
l = len(a_list)
if l > 1: # if there are multiple elements...
l /= 2 # find the midpoint
m1 = find_max(a_list[:l]) # find the max in the first half
m2 = find_max(a_list[l:]) # find the max in the second half
if m1 > m2: # pick between them
return m1
else:
return m2
elif l < 1: # deal with empty lists
return None
else: # we're down to one element...
if isinstance(a_list[0], list): # ...but it may be a list
return find_max(a_list[0]) # if so, find its max
else:
return a_list[0] # otherwise, a single element is trivially the max of its subset
请注意,通过将子问题分成两半而不是减去 1,即使是大型列表,此实现也应该能够很好地防止堆栈溢出。
现在修改为处理空列表。
关于python - 列表python列表的递归最大函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35540268/