Python finds numbers not in set

I have a number of numbers, such as 1-100. And I have a set that contains everything, or a random subset of numbers in this range, for example:

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

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

+6
source share
5 answers

Using Difference Operations

 set(range(1, 101)) - s 
+17
source

Set the difference

 set(range(1, 101)) - s 
+13
source
 all = set(range(1,101)) missing = all -s 
+5
source

I would add all elements not included in the set to the 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
source

Despite the ugliness, it is more effective than the established 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 
+1
source

Source: https://habr.com/ru/post/886911/


All Articles