为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕慕森 2022-12-20 14:25:26
我最近开始编码并且正在研究一个函数,该函数返回给定数组中的 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]。为什么是这样?太感谢了!
查看完整描述

2 回答

?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

在 for 的末尾添加一个 break


  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


查看完整回答
反对 回复 2022-12-20
?
慕姐8265434

TA贡献1813条经验 获得超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 个时,我们都会在添加更多元素之前删除一个元素。


查看完整回答
反对 回复 2022-12-20
  • 2 回答
  • 0 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信