Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the missing numbers in an arbitrary list in python 3?

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.

like image 331
Mahir Islam Avatar asked Nov 22 '25 12:11

Mahir Islam


2 Answers

How about this:

a = [10, 12, 13, 8]
b = set(range(min(a), max(a)+1))
print(set(a).symmetric_difference(b))
like image 154
petezurich Avatar answered Nov 25 '25 02:11

petezurich


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)))
like image 24
Mahir Islam Avatar answered Nov 25 '25 02:11

Mahir Islam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!