[英]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.