简体   繁体   English

python-递归搜索列表的最大值

[英]python - Search for the max of a list recursively

Can Anyone please tell me why this code is returning RuntimeError: maximum recursion depth exceeded : 任何人都可以告诉我为什么此代码返回RuntimeError: maximum recursion depth exceeded

def maximum(tab, indDeb, indFin):
    if (indDeb == indFin):
        return indDeb
    else:
        m = (indDeb + indFin) / 2
        print "m = ", m
        k1 = maximum(tab, indDeb, indFin)
        k2 = maximum(tab, m+1, indFin)
        if (tab[k1] > tab[k2]):
            return k1
        else:
            return k2

if __name__ == "__main__":
    maximum([1, 2, 3, 4, 5], 0, 4)

Within maximum you are calling the function recursively without altering the arguments: maximum范围内,您在不更改参数的情况下递归调用函数:

def maximum(tab, indDeb, indFin):
    # ...

    k1 = maximum(tab, indDeb, indFin)

This cannot but lead to infinite recursion. 这不能不导致无限递归。

Perhaps you wanted to limit the upper index instead: 也许您想限制上限索引:

k1 = maximum(tab, indDeb, m)

The line: 该行:

k1 = maximum(tab, indDeb, indFin)

should be: 应该:

k1 = maximum(tab, indDeb, m)

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

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