我最近开始编写代码,正在编写一个函数,该函数返回给定数组中的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]
为什么会这样
非常感谢你
这个嵌套循环可以向
list
添加任意多的元素(顺便说一句,这对于列表来说是个坏名字,因为它覆盖了内置函数list()
):您只检查外循环中
list
的长度,但内循环遍历整个数组,并可能在再次检查该条件之前将它们全部添加到list
(如果数组按相反顺序排序)编写此函数的一种更简单的方法是简单地对其进行排序并获取最高的三个元素:
(编辑)不涉及排序的稍微复杂的版本:
在这个实现中,
largest_3
永远不允许增长超过3个元素,因为每次增长到4个元素时,我们在添加更多元素之前只删除一个元素在for的结尾添加一个中断
相关问题 更多 >
编程相关推荐