23

I have a range of numbers such as 1-100. And I have a set that holds all, or a random subset of numbers in that range such as:

s = set([1,2,3,35,67,87,95])

What is a good way to get all of the numbers in the range 1-100 that are not in that set?

Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83
Chris Dutrow
  • 48,402
  • 65
  • 188
  • 258

5 Answers5

37

Use set difference operation

set(range(1, 101)) - s
Imran
  • 87,203
  • 23
  • 98
  • 131
16

Set difference

set(range(1, 101)) - s
Praveen Gollakota
  • 37,112
  • 11
  • 62
  • 61
8

I would add all the items not in the set into a list.

s = set([1,2,3,35,67,87,95])

x = []
for item in range(1, 101):
    if item not in s:
        x.append(item)

print x
3

Although ugly it is more efficient than set difference:

def not_in_set (s, min = 0):
    '''Returns all elements starting from min not in s.
    '''
    n = len(s)
    if n > 0:
        l = sorted(s)
        for x in range(min, l[0]):
            yield x
        for i in range(0, n - 1):
            for x in range(l[i] + 1, l[i + 1]):
                yield x
        r = l.pop() + 1
    else:
        r = min
    while True:
        yield r
        r += 1
makeroo
  • 509
  • 8
  • 10
0

In order to find elements of a set that are not in another set, one might use the Set difference() method or using the - operator (as @Imran).

Using the difference method:

s = {1,2,3,35,67,87,95} # Set that you use as example
t = set(range(1, 101)) # Set from 1 to 100

print(t.difference(s))
>>> {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 88, 89, 90, 91, 92, 93, 94, 96, 97, 98, 99, 100}
Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83