简体   繁体   中英

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.

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.

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 . This is what causes a[j] to trigger IndexError as a = [] in the second iteration of the for loop.

Then your outer for loop should use range(n, -1, -1) which returns [2, 1, 0] if n==2 (see the documentation here ).

Also B needs to be empty for each iteration of the outer loop.

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

>>> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM