[英]how to find largest number in a list using recursion?
def find_highest(lst):
if lst[0] < lst[-1]:
return find_highest(lst.pop(0))
elif lst[0] > lst[-1]:
return find_highest(lst.pop())
else: return lst
此代碼引發 TypeError。 誰能說出為什么會這樣?
您的代碼存在會引發IndexError
的問題。 您正在使用pop
從列表中拉出元素,因此在某些時候列表將為空。
您應該檢查列表長度。
在這里你有使用不同方法的解決方案 - 我仍然使用pop
但總是在列表的同一端。 -
def find_largest(target_list):
# If the len of list is 0, we have consume all numbers.
if len(target_list) == 0:
return None
# Just get a number from the list, no matter which ...
number = target_list.pop()
# ... then recursively call the function to get the largest among the
# remaining numbers in the list.
largest = find_largest(target_list)
# Compare the number you pull out the list with the "largest" of the remaining and
# keep the largest.
if largest is None or number >= largest :
return number
return largest
if __name__ == "__main__":
import random
target_list = [random.randint(0, 10) for i in range(10)]
print(f"Target list: {target_list}")
largest = find_largest(target_list)
print(f"Largest number: {largest}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.