gpt4 book ai didi

python - 循环时避免 Python 中的索引错误

转载 作者:行者123 更新时间:2023-11-28 22:30:37 25 4
gpt4 key购买 nike

无论这是否是在 Python 中构造此排序算法的最有效方法(不是),我对索引要求/内置“min”函数的性质的理解都无法解释以下错误以下代码:

Error: builtins.IndexError: list index out of range

代码如下:

#Create function to sort arrays with numeric entries in increasing order
def selection_sort(arr):
arruns = arr #pool of unsorted array values, initially the same as 'arr'
indmin = 0 #initialize arbitrary value for indmin.
#indmin is the index of the minimum value of the entries in arruns
for i in range(0,len(arr)):
if i > 0: #after the first looping cycle
del arruns[indmin] #remove the entry that has been properly sorted
#from the pool of unsorted values.
while arr[i] != min(arruns):
indmin = arruns.index(min(arruns)) #get index of min value in arruns
arr[i] = arruns[indmin]

#example case
x = [1,0,5,4] #simple array to be sorted
selection_sort(x)
print(x) #The expectation is: [0,1,4,5]

我查看了其他几个索引错误示例,但无法将我的问题归因于进入/退出 while 循环时发生的任何事情。我认为我的排序过程映射是合理的,但我的代码甚至在上面分配给 x 的简单数组上失败。如果可以请帮忙。

最佳答案

arrarruns 是相同的列表。您正在从列表中删除项目,减小其大小,但保持 i 变量的最大值不变。

修复:

arruns = [] + arr

这将为 arruns 创建新数组

关于python - 循环时避免 Python 中的索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42079646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com