简体   繁体   English

如果参数太长,Python函数中的无限递归

[英]Infinite Recursion in Python Function if Argument Too Long

I wrote this recursive function that returns the largest value in a list of integers: 我写了这个递归函数,它返回整数列表中的最大值:

def max_r(l: [int]) -> int:
    if len(l) == 1:
        return l[0]
    else:
        return l[0] if max_r(l[1:]) < l[0] else max_r(l[1:])

The call max_r([1,4,3,2,3,4,89,2,30,1] returns 89 , but calling the function on a longer list: 调用max_r([1,4,3,2,3,4,89,2,30,1]返回89 ,但调用更长列表中的函数:

max_r([96, 84, 87, 81, 94, 74, 65, 42, 45, 76, 5, 37, 86, 8, 46, 54, 62, 63, 35, 85, 16, 23, 18, 57, 51, 90, 58, 33, 47, 10, 64, 49, 67, 29, 71, 30, 9, 99, 75, 3, 97, 32, 59, 25, 27, 72, 61])

results in infinite recursion. 导致无限递归。 Why? 为什么?

It isn't infinitely recursive, but you are doing the same recursive call twice when you don't need to. 它不是无限递归,但是当你不需要时,你正在进行两次相同的递归调用。 Seems to complete quickly enough with the following change: 似乎可以通过以下更改快速完成:

def max_r(l: [int]) -> int:
    if len(l) == 1:
        return l[0]
    else:
        result = max_r(l[1:])
        return l[0] if result < l[0] else result

This isn't just a matter of calling the function recursively twice as many times, I'm not sure on the exact growth rate but it seems be exponential since each extra recursive call will be making more extra recursive calls. 这不仅仅是递归调用函数两次的问题,我不确定确切的增长率,但它似乎是指数的,因为每个额外的递归调用将进行更多额外的递归调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM