[英]How to find the index of the smallest element recursively in python
我想找到元素中最小數字的索引。 如果列表是:[5,6,4,3,8,9] 我將如何找到它並返回帶有如下參數的 function 的索引:
def smallest(table, first, last)
表:列表
第一個:列表的索引 0
last:是列表的最后一個索引
下面遞歸地平分輸入列表以找到最小值的索引:
def smallest(table, first, last):
if last - first <= 1:
return first if table[first] <= table[last] else last
mid = first + (last - first) // 2
left = smallest(table, first, mid)
right = smallest(table, mid + 1, last)
return left if table[left] <= table[right] else right
print(smallest([5, 6, 4, 3, 8, 9], 0, 5)) # 3
另一種方法是在每次遞歸時將間隔( first
- last
)縮短一個,同時比較頭部和尾部的最小間隔:
def smallest(table, first, last):
if first == last:
return first
smallest_tail = smallest(table, first + 1, last)
return first if table[first] <= table[smallest_tail] else smallest_tail
print(smallest([5, 6, 4, 3, 8, 9], 0, 5)) # 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.