python中怎么找出列表中最小的元素_在列表中查找最小元素(递归)-Python

本文探讨了使用递归在Python列表中寻找最小值时遇到的递归深度错误。通过将列表不断一分为二,直到只剩下一个元素,从而找到最小值。示例代码中展示了递归实现,并提醒在实际应用中可以使用内置的`min()`函数。
摘要由CSDN通过智能技术生成

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

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?

解决方案

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]))

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

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 /?)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值