简体   繁体   English

如何使用递归 python 在列表中查找最大元素?

[英]how to Find the largest element in a list using recursion python?

i = 0

def find_max(seq):
if i == len(seq) - 1:
      return seq[0]
else:
      first = seq[i]
      i = i + 1
      max_of_rest = find_max(seq)
      return max(first, max_of_rest)

I do not know what is wrong with this function?不知道这个function有什么问题? It is a infinite loop.这是一个无限循环。

Please check out the following solution and follow comments:请查看以下解决方案并关注评论:

def find_biggest(_list, max_element, first_run):
    """
    _list is a list of floats or integers or both,
    max element is used to store max value,
    first run checks if _list is not empty
    """
    if first_run and not _list:  # check if _list is not empty
        raise ValueError("_list should have float or integer values inside")

    first_run = False

    if not _list:  # exit from recursion, we checked all elements
        return max_element

    element = _list.pop()  # take one element

    if type(element) not in (int, float,):  # check element type
        raise TypeError("_list should contain only int or float values")

    if element >= max_element:  # check if it is more than max
        max_element = element

    return find_biggest(_list, max_element, first_run)  # next step of recursion


if __name__ == "__main__":
    # test
    print(find_biggest([-1, 4, 2, 3, 1, 0, 10, 3, 1, 7], 0, True))
    # print(find_biggest([], 0, True))  # empty case
    # print(find_biggest([-1, 4, 2, 3, "1", 0, 10, 3, 1, 7], 0, True))  # string in list

You can check this:你可以检查这个:

def find_max(seq):
    if len(seq) == 1:
        return seq[0]
    else:
        if seq[0] > seq[1]:
            seq.pop(1)
        else:
            seq.pop(0)
        return find_max(seq)

Your code has a lot of indentation issues, that may skip execution of some lines.您的代码有很多缩进问题,可能会跳过某些行的执行。 Your code should look like this:您的代码应如下所示:

i = 0

def find_max(seq):
    global i
    if i == len(seq) - 1:
        return seq[0]
    else:
        first = seq[i]
        i = i + 1
        max_of_rest = find_max(seq)
        return max(first, max_of_rest)

You missed the global, and thus there is no definition of i inside the function.您错过了全局,因此在 function 中没有i的定义。

You are using uneeded i variable, in recursion you have base case (your first if ), and recursion case, which in this case would be accessing first and second element of your list.您正在使用 uneded i变量,在递归中您有基本情况(您的第一个if )和递归情况,在这种情况下将访问列表的第一个和第二个元素。 As you already checked that the list seq has more than 1 element, you can confidently access positions 0 and 1 of the list.由于您已经检查过列表seq有超过 1 个元素,因此您可以放心地访问列表的位置 0 和 1。

In your specific case, you are not really using recursion because you never reduce your case, but instead you increment an i variable, whilst recursion is based on always calling the same function with a "simpler" or reduced problem.在您的特定情况下,您并没有真正使用递归,因为您从不减少您的情况,而是增加一个i变量,而递归基于始终以“更简单”或减少问题调用相同的 function 。

With that in mind, several things can be improved in your solution.考虑到这一点,可以在您的解决方案中改进几件事。

i = 0 # Not adviced

def find_max(seq):
    # Here you want to check length, making it
    # depend on i = problems
    if i == len(seq) - 1: 
        return seq[0]
    else:
        first = seq[i] # Remove all references to i
        i = i + 1 # Remove
        # Here you want to call the function with the list
        # except the element you know is lower, making the problem
        # smaller until you get to the base case
        # Instead you are calling find_max with the same
        # sequence you had (infinite loop) and returning a
        # totally different result.
        max_of_rest = find_max(seq)
        return max(first, max_of_rest)

A complete solution based on your code would look like this基于您的代码的完整解决方案如下所示

def find_max(seq):
    if len(seq) == 0:
        return None
    if len(seq) <= 1:
        return seq[0]
    else:
        current_max = max(seq[0], seq[1])
        reduced_seq = [current_max] + seq[2:]
        return find_max(reduced_seq)

Your code contains an IndentationError and does not reduce its data on recursive calls - hence data never getting shorter - hence never ending recursion:您的代码包含IndentationError并且不会减少递归调用的数据 - 因此数据永远不会变短 - 因此永远不会结束递归:

 def find_max(seq): if i == len(seq) - 1: # fixed indentation here and below return seq[0] else: first = seq[i] i = i + 1 max_of_rest = find_max(seq) # never reducing your data size, hence endless return max(first, max_of_rest)

This would be a fixed recursive solution:这将是一个固定的递归解决方案:

def find_max(seq):   
    if not seq:
        return None  # or raise ValueError if you want find_max([]) to crash
    if len(seq) == 1:
        return seq[0]
    else:
        return max(seq[0], find_max(seq[1:]))

The problem is inheritently bad for recursive solutions, it is far better to solve it linearly (no max(..) calls needed):这个问题对于递归解决方案来说是天生不好的,线性解决它要好得多(不需要max(..)调用):

def find_max_lin(seq):
    if not seq:
        return None
    m = seq[0]
    for value in seq[1:]:
        m = m if value < m else value
    return m

or even better simply use the built in max(sequence) :甚至更好的是简单地使用内置的max(sequence)

def find_max_builtin(seq): 
    # no need to create your own function for that though
    return max(seq)

See ternary operator for an explanation of what m = m if value < m else value does.请参阅三元运算符以了解m = m if value < m else value的作用。

i = 0

def find_max(seq):
    global i
    if i == len(seq) :
        return seq[0]
    else:
          first = seq[i]
          i = i + 1
          max_of_rest = find_max(seq)
          return max(first, max_of_rest)



print(find_max([-10,2,4,-5]))

thank me later晚点再谢我

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

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