如何递归应用此功能

TBOTL

所以我有了这个功能aux,很容易理解。该函数的作用是查看比列表的第一个元素大多少个数字。

list1 = [5,2,7,4,3,8]

def aux(list1):
    x=list1[0]
    res=1
    for number in range(1,len(list1)):
        if(list1[number]>x):
            res+=1
    return res

现在我想制作另一个aux对列表的每个元素递归使用的函数,看看谁返回的数字更大。但是我没有看到我该如何递归地做到这一点。

装饰工厂

我知道这不是问题的一部分,但是我会这样重写函数:

def count_gt(x, container):
    greater_than_x = 0
    for number in container:
        if number > x:
            greater_than_x += 1
    return greater_than_x

让我们看一些使递归变得更简单的递归示例。

列表总和:

def get_sum(container):
    if container == []:
        return 0
    else:
        return container[0] + get_sum(container[1:])

使用循环,可以轻松解决问题:

greatest = 0
for number in numbers:
    greatest = max(count_gt_first(number), greatest)

如果您的任务是在正数列表中找到最大数,则可以这样递归表示:

def get_max(container):
    if len(container) == 1:
        return container[0]
    else:
        return max(container[0], get_max(container[1:]))

例如:

get_max([4, 3, 9, 1])
    --> max(4, get_max[3, 9, 1])
    --> max(5, max(3, get_max[9, 1]))
    --> max(5, max(3, max(9, get_max[1])))
    --> max(5, max(3, max(9, 1)))
    <-- max(5, max(3, 9))
    <-- max(5, 9)
    <-- 9

现在,您可以修改函数以找到最大值,而不是函数的最大结果值。

def get_max(container):
    return _get_max(container, container)

def _get_max(container, original_container):
    if len(container) == 1:
        return container
    else:
        result_for_this = count_gt(container[0], container)
        candidate_for_rest = _get_max(container[1:], container)
        result_for_rest = count_gt(candidate_for_rest, container)
        if result_for_this > result_for_rest:
            return container[0]
        else:
            return candidate_for_rest

您可以重写该函数以使用尾部递归

def get_max(container):
    return _get_max(container, container, container[0])

def _get_max(container, original_container, max_candidate):
    if count_gt(container[0], container) > count_gt(max_candidate, container):
        max_candidate = container[0]
    if len(container) == 1:
        return max_candidate
    return _get_max(container[1:], original_container, max_candidate)

阅读有关递归的更多信息:

https://realpython.com/python-thinking-recursively/

https://chrispenner.ca/posts/python-tail-recursion

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章