繁体   English   中英

Python 2在子数组中查找最小值的索引

[英]Python 2 Finding the index of minimum value in a subarray

我是编程的新手,刚开始学习算法。 我要解决的问题来自Khan Academy算法课程(使用JavaScript,但我使用Python进行了学习),它要求我在子数组中找到最小值的索引。

具体来说,任务如下:完成编写函数indexOfMinimum,该函数采用一个数组和一个数字startIndex,并返回在索引index或更大时出现的最小值的索引。 如果该最小值在该范围内多次出现,则返回该范围内最左侧出现的索引。

大约一个星期以来,我一直在网络上寻找该问题的答案,并且没有设法在Python 2中找到解决该问题的任何资源。如果有人可以帮我解决这个问题,我将不胜感激。 编辑:在阅读了您的一些回复后,我得到以下信息:(它对我有用,但是如果有人发现问题,请在下面评论)

def indexOfMinimum(lst,index):      
    sublist = lst[index:]  
    for minValue in lst:  
        minIndex = sublist.index(min(sublist))  
        return minIndex  
print indexOfMinimum([2,4,6,8,1,3,5,0,7,9], 4)

这将需要三个Python工具:一个列表切片,以及方法minindex 使用您的开始索引,将sub_list设置为给定列表的必需切片。 min应用于子列表 ,获取列表的最小值。 最后,在该最小值上使用sublist.index来获取最左侧外观的索引。

这足以使您动起来吗?

因此,您想要在数组的第一个元素(也可以从右到左)中设置一个变量(此处为“结果”),并与每个元素进行比较。 如果要比较的元素结果较小,则将结果设置为等于它。

为了帮助您入门,这是一种简单的解决方案:

 array = [1, 2, 3, 4] result = array[0] for i in array: if result > i: result = i i += 1; print(result) 

希望有帮助!

有很多方法可以实现,这是一种:

def indexOfMinimum(lst,index):
smallest=lst[index] #assuming index is within range
smallestIndex=index
while index<len(lst):
    if lst[index]<smallest:
        smallest=lst[index]
        smallestIndex=index
    index+=1
return smallestIndex

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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