Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I am trying to swap two objects in python like this A[i], A[A[i] - 1] = A[A[i] - 1], A[i] is not giving me the correct output

According to the order of operation: https://docs.python.org/3/reference/expressions.html#evaluation-order the right hand side is resolved first and then do the assignment from left to right. Suppose i = 1 then we get A[1], A[3] = A[3], A[1]

Suppose A = [-1, 4, 3, 1] and i = 1 where i is an index

A[i], A[A[i] - 1] = A[A[i] - 1], A[i] 

I get [4,1,3,1] as the result even though I expected to get [-1, 1,3,4] i.e. A[1], A[3] = A[3], A[1]

But when I do this I get the correct [-1,1,3,4]. Why does this one work and the above does not?

A[A[i] - 1], A[i] = A[i], A[A[i] - 1]

2 Answers

0 votes
by (25.1k points)

You are facing this issue because python does assignments from left to right

So according to your example i = 1

So A[i] = A[1] = 4 and A[A[i] - 1] = A[A[1] - 1] = A[4 - 1] = A[3] = 1

So now the assignments from left to right

A[1] = A[1] <- 1

A[A[i] - 1] = A[1-1] = A[0] <- 4

So the result becomes = [4, 1, 3, 1]

0 votes
by
электронной сигареты dse-801 москва [url=https://hqd.wiki/kupit-hqd-optom/]hqd мелкий опт[/url]
------
купить электронную сигарету в прохоровке [url=https://hqd.wiki/kupit-hqd-optom/]hqd опт сайт[/url]

Related questions

Browse Categories

...