+ 2

elements exchange

I met this in game section: arr = [4,3,1,2] arr[0], arr[arr[0]-1] = arr[arr[0]-1], arr[0] print(arr) but coldn’t understand why correct answer is [2,4,1,2] I guess this code changes or reassigns the 0-th and the 3-rd elements (4,2). How it connected with the 1-st element (3)?

20th Feb 2019, 10:55 PM
Anna Starikova
Anna Starikova - avatar
3 odpowiedzi
+ 6
The trick for understand this is valutate first the right side of assignment. Following your example: arr[0], arr[arr[0]-1] = arr[arr[0]-1],arr[0] and apply the "trick": arr[0], arr[arr[0]-1] = arr[4-1],4 arr[0], arr[arr[0]-1] = 2,4 Then assign: arr[0]= 2 arr[arr[0]-1]= arr[2-1]= arr[1]= 4 Get the resulting array [2,4,1,2]
20th Feb 2019, 11:12 PM
KrOW
KrOW - avatar
+ 4
KrOW thank’s. I understand my mistake: i thought that when assigne elements in one string it takes them in one moment (parallel). But it works consecutively like it was two separate strings with assignments. Right?
20th Feb 2019, 11:27 PM
Anna Starikova
Anna Starikova - avatar
+ 2
Anna Starikova Yes, nothing happen in "parallel" in assignment. The imortant thing to remember is than its valuted FIRST the right side then assigned sequentially to left side.
21st Feb 2019, 8:16 AM
KrOW
KrOW - avatar