2016-02-21 94 views
2

我想写一个递归函数,以便在列表中找到最大整数。我知道如何为整数列表编写func。任何人都可以给我一些这方面的提示吗?我 我想这样做没有最大功能。 ex。 a = [1,[2,3],4,[[2],1]] find_max(a) - > 4列表python的递归最大函数

+0

但是这不是一个很好的问题,但请指定一些样本,以更好地解决您的问题 – Arman

回答

0

如果数据类型是列表,则可以遍历列表并调用MAX()函数:

l = [[54,65,464,656,5],[568,49,7,8,4,3,3515],[312,64,598,46]] 

def MAX(l): 
    mx = None 
    for item in l: 
     if isinstance(item, list): 
      tmp = MAX(item) 
     else: 
      tmp = item 

     if mx < tmp: 
      mx = tmp 
    return mx 
+0

感谢您的帮助! :) – bxlt

+0

@bxlt我很乐意帮助你。欢迎接受一个答案(社区)。 – Zety

+0

如果列表中的所有数字均为-1以下的负值,则这将返回-1。 – pjs

1

我决定用纯递归,没有循环来解决这个。下面,似乎这样的伎俩对我来说:

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减少,这应实现对堆栈大名单甚至溢出是稳健的。


现在修改为处理空列表。

+0

它真的很有帮助!我试图用这种方式编写函数,但是我失败了。 XD – bxlt

+0

如果有一个空的子列表会怎么样? – bxlt