Python list values ​​don't change

I am trying to solve the problem. When trying to change the values ​​of a list, I observed strange behavior of the list. I cannot change the values ​​of the list items.

top = list(map(int, raw_input().split()))
staff = list(map(int, raw_input().split()))

ceo  = top[0]
coo = top[1]
cto = top[2]

top.extend(staff)
alls = sorted(top)
tot = len(alls)
print(alls)

alls[tot/2], alls[alls.index(ceo)] = alls[alls.index(ceo)], alls[tot/2]
print(alls)

alls[0], alls[alls.index(coo)] = alls[alls.index(coo)], alls[0]
alls[-1], alls[alls.index(cto)] = alls[alls.index(cto)], alls[-1]

print(alls)

      

Here is the output of the program:

Input:

13 11 17
12 10

      

Output

[10, 11, 12, 13, 17]
[10, 11, 12, 13, 17]
[10, 11, 12, 13, 17]

      

Why don't all the values ​​in the list change? Am I doing something wrong?

EDIT: Question: https://www.hackerearth.com/codejunk/algorithm/steal-the-show/

I know my approach is not the best way to solve this problem, but I just want to know why the list values ​​are not changing?

+3


source to share


1 answer


The problem is with your combination of operators. I take the first assignment as an example and analyze it:

alls[tot/2], alls[alls.index(ceo)] = alls[alls.index(ceo)], alls[tot/2]

      

What will happen:

  • ceo is 13 at the beginning, so alls.index (ceo) will be 3 when the statement is executed ... but wait ... this is done before the appointment.

  • Values ​​will be evaluated first before assignment. alls [alls.index (ceo)] would be 13 - not surprising, because ceo would be 13.

  • alls [tot / 2] will be 12 because tot / 2 is 2 (the indices will be integers, so the part behind the comma will be lost).

  • So, on the right side we get (13, 12).

  • Now, to the task. alls [tot / 2] will be assigned first (but you can't trust it as this is an implementation detail!).

  • So all [2] will be 13 !!

  • Now the second part of the assignment .... alls.index (ceo) will be 2 .... WHAT ???



The reason is that currently all the others [10, 11, 13, 13, 17] ... and alls.index (ceo) will evaluate and find 13 at position 2 before it finds the other 13 at position 3.

So what happens - alls [2] will be assigned 12 - the list goes back to the previous content again.

The reason is that you are using combined operators and you always evaluate the subexpressions new without considering that the subexpressions will change during the evaluation.

This can be prevented by assigning the results of some subexpressions to variables and using them instead of complicating the expressions. In particular, subexpressions that the main expression can evaluate must be evaluated before the expression and stored in a variable.

+4


source







All Articles