【问题标题】:python list index out of range in k-tuple sortingk元组排序中的python列表索引超出范围
【发布时间】:2017-03-13 19:02:29
【问题描述】:

我想在最短的时间内实现 k 元组排序,即 O(k(m+n)) 时间。

我的代码是:

A = [(1,2,1),(2,3,1),(1,4,2),(2,2,2),(1,4,3),(3,2,1)]
B = [[] for _ in range(5)]

n = len(A[0]) - 1

for j in (n,0,-1):
    while(len(A) != 0):
        a = A.pop(0)
        B[a[j]].append(a)
    for l in range(5):
        A.append(B[l])

print(A)

B[a[j]].append(a) 出现错误,因为索引超出范围。

【问题讨论】:

    标签: python sorting radix-sort


    【解决方案1】:

    我了解到您正在尝试实现基数排序。

    A.append(B[l]) 行是错误的,因为您将列表 B[l] 添加为列表 A 的最后一个元素,而不是在列表 @987654326 的末尾添加 B[l] 的元素@。这就是导致 a[j] 在 for 循环的第二次迭代中将 IndexError 触发为 a = [] 的原因。

    那么你的外部for循环应该使用range(n, -1, -1),如果n==2返回[2, 1, 0](参见documentation here)。

    对于外循环的每次迭代,B 也需要为空。

    A = [(1,2,1),(2,3,1),(1,4,2),(2,2,2),(1,4,3),(3,2,1)]
    
    n = len(A[0]) - 1
    
    for i in range(n, -1, -1):  # range(start, stop, step)
        B = [[] for _ in range(5)] # B needs to be empty for each iteration
        while(len(A)):
            a = A.pop(0)
            B[a[i]].append(a)
    
        for j in range(5):
            A += B[j] # Adding elements of B[j] to the end of A
    
    print(A)
    

    【讨论】:

    • @sam 我编辑了答案,因为我意识到你可能是在基数排序之后。
    【解决方案2】:

    您似乎忘记在 B[0] 处附加某些内容,您开始将列表附加到位置 1 和 2。这就是您正在做的事情

    >>> A = [(1,2,1),(2,3,1),(1,4,2),(2,2,2),(1,4,3),(3,2,1)]
    >>> B = [[] for _ in range(5)]
    >>>
    >>> n = len(A[0]) - 1
    >>>
    >>> for j in (n,0,-1):
    ...     print("j:%d" % j)
    ...     while(len(A) != 0):
    ...         a = A.pop(0)
    ...         print("appending %s at position %s" % (str(a), str(a[j])))
    ...         B[a[j]].append(a)
    ...     print("B:" + str(B))
    ...     for l in range(5):
    ...         print("l:%d" %l)
    ...         A.append(B[l])
    ...     print("A:" + str(A))
    ...
    j:2
    appending (1, 2, 1) at position 1
    appending (2, 3, 1) at position 1
    appending (1, 4, 2) at position 2
    appending (2, 2, 2) at position 2
    appending (1, 4, 3) at position 3
    appending (3, 2, 1) at position 1
    B:[[], [(1, 2, 1), (2, 3, 1), (3, 2, 1)], [(1, 4, 2), (2, 2, 2)], [(1, 4, 3)], []]
    l:0
    l:1
    l:2
    l:3
    l:4
    A:[[], [(1, 2, 1), (2, 3, 1), (3, 2, 1)], [(1, 4, 2), (2, 2, 2)], [(1, 4, 3)], []]
    j:0
    Traceback (most recent call last):
      File "<stdin>", line 5, in <module>
    IndexError: list index out of range
    

    【讨论】:

    • 虽然变量的显示有助于理解程序的功能,但这并不是问题的答案。
    • 我上面怎么说,他没有填充列表 B 的第一个元素,所以程序失败了。从这里开始,正如您正确建议的那样,他可以执行修复以正确的方式填充它。无论如何,答案并不清楚他的要求和细节不足。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 2016-04-04
    • 2016-03-31
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2015-10-09
    相关资源
    最近更新 更多