[英]python list index out of range in k-tuple sorting
I want to implement k-tuple sorting in least time ie O(k(m+n)) time. 我想在最短时间内实现k元组排序,即O(k(m + n))时间。
My code is: 我的代码是:
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)
I am getting error at B[a[j]].append(a)
as index is out of range. 我在
B[a[j]].append(a)
得到错误B[a[j]].append(a)
索引超出范围。
I understand that you are trying to implement a radix sort. 我知道您正在尝试实现基数排序。
The line A.append(B[l])
is wrong because you add the list B[l]
as the last element of list A
instead of adding the elements of B[l]
at the end of list A
. 行
A.append(B[l])
因为添加的列表是错误的B[l]
作为列表的最后一个元件A
而不是添加的元素的B[l]
在列表的末尾A
。 This is what causes a[j]
to trigger IndexError
as a = []
in the second iteration of the for loop. 这是导致
a[j]
在for循环的第二次迭代中触发IndexError
为a = []
的原因。
Then your outer for loop should use range(n, -1, -1)
which returns [2, 1, 0]
if n==2
(see the documentation here ). 那么你的外部for循环应该使用
range(n, -1, -1)
,如果n==2
,则返回[2, 1, 0]
n==2
[2, 1, 0]
(参见此处的文档 )。
Also B
needs to be empty for each iteration of the outer loop. 对于外循环的每次迭代,
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)
seems you forget to append something at B[0], you start appending list to position 1 and 2. Here is what you are doing 好像你忘了在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.