简体   繁体   中英

Iterating through array causing IndexError: list index out of range error

I keep receiving a "IndexError: list index out of range" error but I'm unsure why that would be the case

def missingNumber(nums):
   sorted_nums = sorted(nums)
   for num in sorted_nums[1:]:
      print(num,sorted_nums[num]-1)
      if ((sorted_nums[num] - sorted_nums[num]-1) > 1):
         res = (num + num + 1)/2
   return res
print(missingNumber([3,0,1]))

example: nums = [3,0,1]

//sorted_nums = [0,1,3]
//sorted_nums[1:] = [1,3]
for num in sorted_nums[1:]:
  //here num is element not index
  //so sorted_nums[3] is "IndexError: list index out of range"
  print(num,sorted_nums[num]-1)   
  if ((sorted_nums[num] - sorted_nums[num]-1) > 1):
     res = (num + num + 1)/2
return res

so do this

sorted_nums = [0,1,3]
for num in range(1,len(sorted_nums)):
  print(num,sorted_nums[num]-1)    

  if ((sorted_nums[num] - sorted_nums[num-1]) > 1):  // 1-0 is not greater than 1
     res = (sorted_nums[num] + sorted_nums[num-1])/2
     return res

1st iteration

 num = 1, sorted_nums[num] = 1,sorted_nums[num-1] =0 
 1-0 is not greater than 1

2nd iteration

 num = 2, sorted_nums[num] = 3,sorted_nums[num-1] =1 
 3-1 = 2 is greater than 1 
 so res = (3 + 1)/2 = 4/2 = 2
 missing number is 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM