简体   繁体   English

如何在python中递归查找最小元素的索引

[英]How to find the index of the smallest element recursively in python

I want to find the index of the smallest number in an element.我想找到元素中最小数字的索引。 If the list is: [5,6,4,3,8,9] How would I find it and return the index with a function that has parameters like this:如果列表是:[5,6,4,3,8,9] 我将如何找到它并返回带有如下参数的 function 的索引:

def smallest(table, first, last)

table: the list表:列表

first: index 0 of the list第一个:列表的索引 0

last: is the last index of the list last:是列表的最后一个索引

The following bisects the input list recursively to find the index of the minimum:下面递归地平分输入列表以找到最小值的索引:

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

Another way is to shorten the interval ( firstlast ) by one at each recursion, while comparing the head and the smallest from the tail:另一种方法是在每次递归时将间隔( 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM