py-list索引超出k-tuple排序范围

时间:2017-03-13 19:02:29

标签: python sorting radix-sort

我想在最短时间内实现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)收到错误。

2 个答案:

答案 0 :(得分:1)

我知道您正在尝试实施基数排序。

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

然后,您的外部for循环应该使用range(n, -1, -1),如果[2, 1, 0]则返回n==2(请参阅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)

答案 1 :(得分:-1)

似乎你忘了在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