python - 列表python列表的递归最大函数

标签 python recursion

我正在尝试编写一个递归函数,以便在列表列表中找到最大整数。我知道如何为整数列表编写函数。谁能给我一些提示?我 我正在考虑在没有 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/

相关文章:

python - 如何在 Jupyter 笔记本的 LaTeX 中自定义 numpy 数组列括号的显示格式?

python - GTK 推特客户端

javascript - 如何递归删除包含空数组的嵌套对象?

javascript - 如何递归替换对象中的键名?

.net - 父子数据的 xslt 递归模板

python - 在 Python 中解决 LeetCode 3sum 问题

python 输入被读取错误?

C - 使用递归打印链表

python - python,当调用函数x次时,递归限制错误

Python - 提取并修改linux目录中所有文件中的文件路径