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
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 个时,我们都会在添加更多元素之前删除一个元素。
添加回答
举报