【问题标题】:Finding the maximum element with a recursive function使用递归函数查找最大元素
【发布时间】:2016-11-26 06:39:01
【问题描述】:

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

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

它甚至没有为我删除我所要求的。我做错了什么?看不懂!

【问题讨论】:

  • 你写的函数不是递归的。对于要递归的函数,它必须调用自身,即在 def a_function() 块内有一个 a_function() 调用。您可能知道并且仅仅因为到目前为止没有说明,您可以简单地使用max() 并将您的列表L 传递给它,就像max_item = max(L) 一样。不过我想你已经知道了。
  • @Rawing 添加一个while循环不会使这个函数递归。
  • 它确实删除了一个元素——最后一个2。

标签: python list function


【解决方案1】:

你没有再次调用你的函数,这使得递归变得不可能。此外,您没有停止递归的基本情况,在这种情况下将是:

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]

我还在条件句上添加了&lt;= 和&gt;=,以避免在有两个共享最大值的元素时无限递归。

【讨论】:

【解决方案2】:

它完全按照你的要求去做。

你的函数不是递归的,因为你忘了在最后再次调用它。

您正在寻找这样的东西:

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]
    if len(L) == 1:
        return L
    return maxElement(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, 42425]
[1, 2, 95754754745L, 3, 1, 42425]
[1, 2, 95754754745L, 3, 42425]
[1, 2, 95754754745L, 42425]
[1, 95754754745L]
[95754754745L]
[95754754745L]

我会做得更好一点,如下所示:

def maxElement(L):
    length=len(L)

    if length == 1:
        # Have this condition on the top because you are using length - 2 later
        # Just return the only element

        return L

    if L[length-1] > L[length-2]:
        # If the last element is greater than the last but one, delete the last but one
        del L[length - 2]

    else:
        # Simple else would suffice because you are just checking for the opposite
        # Also this condition saves you from:
        #       infinite looping when the last two elements are equal
        del L[length - 1]

    print L

    # Time to call it recursively.
    # But if you just don't want to unnecessarily increase the recursion
    # tree depth, check for length and return it

    if length == 1:
        return L
    return maxElement(L)

【讨论】:

  • 虽然此函数为问题中提供的输入值生成正确的值,但如果在两个或多个索引中找到最大值,它将导致无限递归。看我的回答。
  • 是的。检查并支持相同的:) 编辑我的答案来处理它。
【解决方案3】:

你为什么不简单地使用 max()?

最大([1,2,95754754745,3,1,8,444,2,42425])

95754754745L

【讨论】:

  • 也许 OP 想练习递归。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-19
  • 1970-01-01
  • 2016-07-05
  • 2012-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多