2

I have the following code for a small program:

def get_different_number(arr):
  if len(arr) == 0 or arr is None:
    return 0
  n = len(arr)
  for i in range(n):
    print (str(i))
    temp = arr[i]
    while (temp < n and temp != arr[temp]):
      temp, arr[temp] = arr[temp],temp
  for i in range(n):
    if arr[i] != i:
      return i
  return n

test = [0,1,2,4,5]
get_different_number(test)

however, when it executes, it tells me there is a problem in the line where I swap temp and arr[temp], it gives me a list index out of range error at i is 3 (temp is 4).

When I change that line to arr[temp], temp = arr[temp], temp (reversed assign order), it worked fine. Why is this happening? I thought the a,b = b,a assignment in python assign both elements at the same time?

yuhengd
  • 343
  • 3
  • 10
  • 1
    yes `temp` is assigned before `arr[temp]` (as explained in the original question) which explains your issue – Jean-François Fabre Sep 21 '17 at 20:32
  • 2
    I wouln'd call it 'at the same time' since it still takes two steps. 1 look whats on the right hand side and the assign it (left to right) on the left hand side. So `arr[temp]` is evaluated after `temp` is set to `5` which is out of range. – Marvin Taschenberger Sep 21 '17 at 20:39

0 Answers0