使用递归函数查找最大元素 [英] Finding the maximum element with a recursive function

查看:282
本文介绍了使用递归函数查找最大元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个函数,试图找出列表中具有最大值的东西:

I wrote a function that tries to find out what has the maximum value in a list:

def maxElement(L):
    length=len(L)
    if L[length-1]>L[length-2]:
        del L[length-2]
        print L
    elif L[length-1]<L[length-2]:
        del L[length-1]
    return L

print maxElement([1,2,95754754745,3,1,8,444,2,42425])

我的输出错误:

>>> 
[1, 2, 95754754745L, 3, 1, 8, 444, 42425]
[1, 2, 95754754745L, 3, 1, 8, 444, 42425]
>>> 

它甚至都没有删除我想要的内容.我做错什么了?我不明白!

It doesn't even delete for me what I've ask for. What did I do wrong? I can't get it!

推荐答案

您不会再次调用函数,因此无法进行递归.此外,您没有停止递归的基本情况,在这种情况下,将是:

You are not calling your function again, which makes recursion impossible. Furthermore you have no base case which would stop recursion, which in this case would be:

if length == 1:
  return L

这是固定代码:

def maxElement(L):
    length=len(L)
    if length == 1:
        return L
    elif L[length-1]>=L[length-2]:
        del L[length-2]
    elif L[length-1]<=L[length-2]:
        del L[length-1] 
    return maxElement(L)    

print maxElement([1,2,95754754745,3,1,8,444,2,42425])

这将输出:

python recursive.py
 > [95754754745L]

我还在条件条件上添加了<=>=,以避免在有两个元素共享最大值的情况下进行无限递归的情况.

I also added <= and >= on the conditionals to avoid infinite recursion if there are two elements that share the maximum value.

这篇关于使用递归函数查找最大元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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