For a list of integers, such as A = [2, 10, -5]
, I get the error
Traceback (most recent call last):
File "so.py", line 6, in <module>
v, A[v-1] = A[v-1], v
IndexError: list assignment index out of range
Code:
for i, v in enumerate(A):
while 1<=v<=len(A) and v != A[v-1]:
v, A[v-1] = A[v-1], v
but this works:
for i, v in enumerate(A):
while 1<=v<=len(A) and v != A[v-1]:
A[v-1], v = v, A[v-1]
Why the order of the swapping elements matters here? v
is always being checked to be in bound.
Weirdly enough cannot reproduce a smaller example. But,
A = [6, 5, 4, 3, 2]
becomes an infinite loop.