How to find numbers that are not listed or missing?

I will have a list of numbers, each in its own line (say 0 -100). How to find numbers that are not listed or missing?

+5
source share
4 answers

Add all of them to the set. Then subtract from the set filled 1-100. Here is an example for 0-9:

>>> set(range(10)) - set([1, 4, 5, 6, 8, 2])
set([0, 9, 3, 7])
>>> 

I had it [1, 4, 5, 6, 8, 2]. To find out which numbers in the range 0-9 are missing, I created a set with all 0-9, and then subtracted the set from it [1, 4, 5, 6, 8, 2]. And they found out that they were [0, 9, 3, 7]missing.

Kits for this are quite effective. As an added benefit, duplicates will be handled gracefully.

+12
source

If L is a list of numbers, then

set(L).difference(xrange(101))

saves set creation from xrange

In [1]: L=[1, 4, 5, 6, 8, 2]

In [2]: timeit set(range(101)) - set(L)
10000 loops, best of 3: 21.7 µs per loop

In [3]: timeit set(L).symmetric_difference(range(101))
100000 loops, best of 3: 14.2 µs per loop

In [4]: timeit set(L).difference(range(101))
100000 loops, best of 3: 9.73 µs per loop
+1

awk, (-) :

printf '%s\n' 1 4 5 6 8 2 |
awk -F " " -v first=0 -v last=9 '
BEGIN { 
  for(i=first; i<=last; i++) 
    array[i] = 0
}
{
  for(i=1;i<=NF;i++)
    array[$i] += 1
}
END {
  for (num in array)
    if (array[num] == 0) print num
}
'
  • , 0.
  • Each input number is then treated by awk as a key to the array, so the value is incremented by 1.
  • At the end, only those keys that have not been enlarged will be printed, i.e. have a value of 0 (since they were not in the input range of numbers).
0
source

bash:

# first set up an array containing the whole range
declare -a nums
for i in {0..100}; do
  nums[$i]=1
done

# then read the file and remove the numbers from it
while read number; do
  unset nums[$number]
done < file.with.numbers

# the remaining array keys are the numbers not found in the file
for number in "${!nums[@]}"; do
  echo $number
done
0
source

All Articles