Reputation: 108
I am trying to make list comprehension for the below code, the code works fine if comprehension not used.
This code is used to return the missing number in a sequence of numbers that have a constant difference between the consecutive terms of a given series of numbers.
def find_missing(sequence):
difference = min(sequence[1] - sequence[0], sequence[-1] - sequence[-2])
# for index in range(len(sequence)):
# if sequence[index] + difference != sequence[index+1]:
# return sequence[index] + difference
# return [index for index in range(len(sequence))]
return [sequence[index]+difference for index in range(len(sequence)) if sequence[index]+difference != sequence[index+1]]
print(find_missing([1, 2, 3, 4, 6, 7, 8, 9])) # ==5
print(find_missing([1, 3, 5, 9, 11])) # == 7
print(find_missing([1, 3, 4])) # == 2
I have an error message when using comprehension. Error:
IndexError: list index out of range
Upvotes: 1
Views: 847
Reputation: 92440
You are getting an error because index+1
in sequence[index+1]
is one bigger than the array on the last iteration. Python generally discourages using indexes for loops — partially because it's so easy to create these kind of bugs.
If you want to compare adjacent elements, you can instead loop over zip(sequence, sequence[1:])
. This will give you pairs that you can then compare — it's easier to read and you don't need to worry about index errors:
def find_missing(sequence):
difference = min(sequence[1] - sequence[0], sequence[-1] - sequence[-2])
return [ f + difference
for f, n in zip(sequence, sequence[1:])
if f + difference != n ]
print(find_missing([1, 2, 3, 4, 6, 7, 8, 9])) # == [5]
print(find_missing([1, 3, 5, 9, 11])) # == [7]
print(find_missing([1, 3, 4])) # == [2]
Upvotes: 3