2

I am trying to find the missing numbers in an arbitrary list. In an ordered list my code works fine, but in an arbitrary list in doesn't work. This is my code:

a = [10,12,13,8]
b = [x for x in range(a[0], a[-1] + 1)]
a = set(a)
print(list(a ^ set(b)))

The output is:

[8, 10, 12, 13]

But when a is sorted, the output comes out fine:

[9,11]

What's wrong in my code and how can i fix it? PS. I know i can just sort the list and get the problem fixed but i want it to work on an arbitary list as well.

Mahir Islam
  • 1,941
  • 2
  • 12
  • 33
  • 4
    Define "missing numbers". Does that mean "the integers between the minimum number in the list and the maximum number in the list, that don't occur in the list"? If yes, the problem with your code should be obvious - you never bothered to search for the minimum or maximum numbers in the list. – Aran-Fey Sep 16 '18 at 12:24
  • Indeed. The range as it stands is from 10 to 9 exclusive. Since Python doesn't automatically flip the step to `-1`, this is an empty list! – Luke Sawczak Sep 16 '18 at 12:27
  • @Aran-Fey thanks, I can't believe I didn't see that. Thanks it has been solved – Mahir Islam Sep 16 '18 at 12:27

4 Answers4

2

How about this:

a = [10, 12, 13, 8]
b = set(range(min(a), max(a)+1))
print(set(a).symmetric_difference(b))
petezurich
  • 9,280
  • 9
  • 43
  • 57
1

As Aran-Fey in the comments pointed out my obvious mistake, the problem has been solved. The solution:

a = [10,12,13,8]
b = [x for x in range(min(a), max(a) + 1)]
a = set(a)
print(list(a ^ set(b)))
Mahir Islam
  • 1,941
  • 2
  • 12
  • 33
1

Try changing b to:

b = [x for x in range(min(a), max(a) + 1)]

You're assuming that a[0] is the smallest item and a[-1] is the largest, which could be wrong.

As a side note, you don't need a list comprehension:

b = list(range(min(a), max(a) + 1))
iBug
  • 35,554
  • 7
  • 89
  • 134
1

If you substitute a[0] and a[-1] into range, you will have

b = [x for x in range(10, 9)]
print(b)

which returns

[]

So, you have no value in list b.

yoonghm
  • 4,198
  • 1
  • 32
  • 48