函数为某些数组返回错误的值

2024-09-19 23:40:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始编写代码,正在编写一个函数,该函数返回给定数组中的3个最大数字。该函数适用于大多数阵列,但不适用于其他阵列。代码如下:

def findThreeLargestNumbers(array):
  list = []
  if len(set(array)) != 1:
    while len(list) <= 2:
      for element in array:
        if element == max(array):
          list.append(element)
          array.remove(element)
    list.reverse()
    return list
  else:
    for element in array:
      newlist = [element, element, element]
      return newlist

例如,当我输入数组[1,2,3,4,5]时,函数返回[3,4,5]。但是,当我输入[55,43,11,3,-3,10]时,函数返回4个值:[10,11,43,55]

为什么会这样

非常感谢你


Tags: 函数代码inforlenreturnifdef
2条回答

这个嵌套循环可以向list添加任意多的元素(顺便说一句,这对于列表来说是个坏名字,因为它覆盖了内置函数list()):

    while len(list) <= 2:
      for element in array:
        if element == max(array):
          list.append(element)
          array.remove(element)

您只检查外循环中list的长度,但内循环遍历整个数组,并可能在再次检查该条件之前将它们全部添加到list(如果数组按相反顺序排序)

编写此函数的一种更简单的方法是简单地对其进行排序并获取最高的三个元素:

from typing import List

def find_three_largest_numbers(array: List[int]) -> List[int]:
    """Return the three largest numbers from the array."""
    return sorted(array)[-3:]

(编辑)不涉及排序的稍微复杂的版本:

def find_three_largest_numbers(array: List[int]) -> List[int]:
    """Return the three largest numbers from the array."""
    largest_3: List[int] = []
    for num in array:
        largest_3.append(num)
        if len(largest_3) > 3:
            largest_3.remove(min(largest_3))
    return largest_3

在这个实现中,largest_3永远不允许增长超过3个元素,因为每次增长到4个元素时,我们在添加更多元素之前只删除一个元素

在for的结尾添加一个中断

  def findThreeLargestNumbers(array):
      list = []
      if len(set(array)) != 1:
        while len(list) <= 2:
          for element in array:
            if element == max(array):
              list.append(element)
              array.remove(element)
              break
        list.reverse()
        return list
      else:
        for element in array:
          newlist = [element, element, element]
          return newlist

相关问题 更多 >