【问题标题】:IndexError: list index out of range for insertion sort codeIndexError:插入排序代码的列表索引超出范围
【发布时间】:2021-11-07 23:33:41
【问题描述】:

[我不确定如何解决这个问题(A 级 CS)

numbers = [12,10,16,11,20]

def InsertionSort(numbers):
    for index in range (len(numbers)):
        
        nextposition = numbers[index + 1]
        preposition = index 

        if numbers[nextposition] < numbers[preposition]:
            print('check1')
            while preposition > 0 and numbers[preposition] > numbers[nextposition]:
                temp = numbers[preposition]
                numbers[preposition] = numbers[nextposition]
                numbers[nextposition] = temp
                print ('check')
            numbers[nextposition] = numbers[nextposition + 1]
            
    print (numbers)
    return numbers


InsertionSort(numbers)

Traceback here

【问题讨论】:

  • 请将回溯作为文本而不是图像发布,谢谢。
  • 为什么要写这个:nextposition = numbers[index + 1] 和 ...numbers[nextposition] 你肯定超出范围
  • @user1740577 我用什么替换它?我基本上需要变量指向一个的索引,然后是+1的索引

标签: python insertion-sort index-error


【解决方案1】:

至少有 2 个错误。

nextposition = numbers[index + 1] 

应该是

nextposition = index + 1

并且你迭代了范围的长度,所以当谈到最后一次时,它的下一个位置是 len(range)+1 所以你超出了范围。

【讨论】:

  • 如何更改或更正以使其正常工作?
  • 一般来说,如果你有一个包含 n 个数字的列表,并且你想将每个数字与下一个数字进行比较,你将进行 n-1 个比较。
  • for index in range (len(numbers)): 应该有一个-1。
  • 它仍然无法正常工作,o 添加了 -1 并删除了索引 +1 的两个错误,认为它应该自行迭代但它仍然不起作用 - 没有错误但输出完全是随机的
  • 我假设您正在尝试对列表进行排序。但我认为您的代码正在执行冒泡排序的一次迭代,而不是插入排序。查看维基百科页面上的伪代码:en.wikipedia.org/wiki/Insertion_sort,您会看到有两个 while 循环。您的代码只有一个。
猜你喜欢
  • 1970-01-01
  • 2019-01-06
  • 2011-10-31
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多