在列表中查找最小元素(递归)-Python [英] Finding minimum element in a list (recursively) - Python

查看:292
本文介绍了在列表中查找最小元素(递归)-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用递归在整数列表中找到最小值。主要思想是,如果列表只有一个元素长,则此元素是我的最小值。
另外,我将列表分为两个相同大小的较小列表,在两个列表中寻找最小值,然后比较哪个较小。
代码如下所示:

I'm trying to find the minimum value in a list of integers using recursion. The main idea is that if the list is only one element long, this element is my minimum. Else, I divide the list onto two smaller lists of the same size, look for minimum value in both of them and then compare which one is smaller. The code looks like this:

def minimum(a,l,p):
    if l == p:
        return a[l]
    else:
        m1 = minimum(a,l, (l+p)/2)
        m2 = minimum(a, (l+p)/2 + 1, p)
        if m1 < m2:
            return m1
        else:
            return m2

似乎并不困难,但是当我尝试为示例列表运行此功能时,出现以下错误: RecursionError:在比较中超出了最大递归深度
算法有问题吗,或者出于这个问题的原因,也许我应该去别的地方?

It doesn't seem to be difficult, however when I tried to run this function for a sample list, I got the following error: "RecursionError: maximum recursion depth exceeded in comparison". Is something wrong with the algorithm or maybe I should look somewhere else for the reason fo this problem?

推荐答案

最后,我相信这只是一个示例,说明如何使用递归而不是循环遍历列表并用于学习目的。您可以将列表连续分成两半,直到获得长度为 1 的列表,这是在元素浮出水面时出现的长度。如果您出于学习目的而执行此操作,建议您添加 print()语句以查看列表的功能。

In the end, I believe this is just an example on how to iterate through a list using recursion rather than using a loop and used for learning purposes. You can continuously split the list into halves until you get a list of length 1, which is when you surface the element. If you're doing this for learning purposes, I suggest you add print() statements to see what your list is doing.

def minimum(lst):
    if len(lst) == 1:
        return lst[0]
    else:
        m1 = minimum(lst[0:len(lst) / 2])
        m2 = minimum(lst[len(lst) / 2:])
        if m1 < m2:
            return m1
        else:
            return m2


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

但是正如@HFBrowning在评论中提到的那样,在现实生活中,您应该只使用 min(lst) 并完成它。

But as @HFBrowning mentioned in a comment, in real life you should just use min(lst) and be done with it.

正如@PatrickHaugh在对此答案的评论中提到的那样,该部门必须返回一个整数。这意味着,如果您在Python 3上运行此代码,则应将 len(lst)/ 2 更改为 len(lst)// 2 (请参阅双 / 吗?)

And as @PatrickHaugh mentioned in a comment to this answer, the division must return an integer. Which means, if you're running this on Python 3, you should change the len(lst) / 2 to len(lst) // 2 (see the double /?)

这篇关于在列表中查找最小元素(递归)-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆