2 回答

TA貢獻1829條經(jīng)驗 獲得超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條經(jīng)驗 獲得超2個贊
這個嵌套循環(huán)可以添加任意數(shù)量的元素list(順便說一句,這對于列表來說是一個壞名字,因為它會覆蓋內(nèi)置函數(shù)list()):
while len(list) <= 2:
for element in array:
if element == max(array):
list.append(element)
array.remove(element)
您只檢查外層循環(huán)的長度list,但內(nèi)層循環(huán)遍歷整個數(shù)組,并可能list在再次檢查條件之前將所有這些添加到(如果數(shù)組是反向排序的)。
編寫此函數(shù)的一種更簡單的方法是簡單地對其進行排序并取最高的三個元素:
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
在此實現(xiàn)中,largest_3永遠不允許增長超過 3 個元素,因為每次增長到 4 個時,我們都會在添加更多元素之前刪除一個元素。
添加回答
舉報