Python find numbers not in set
35,805
Solution 1
Use set difference operation
set(range(1, 101)) - s
Solution 2
Set difference
set(range(1, 101)) - s
Solution 3
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
Solution 4
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
Related videos on Youtube
Author by
Chris Dutrow
Creator, EnterpriseJazz.com Owner, SharpDetail.com LinkedIn
Updated on April 29, 2021Comments
-
Chris Dutrow almost 3 years
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?
-
matth almost 13 yearsPerhaps you mean
range(1,101)
? -
ssoler almost 3 yearsReadability counts. (The Zen of Python)