How can I write a function that asks the user to specify multiple set of numbers and return the numbers outside of these ranges?
Let's say I want the numbers that are not included in 3-8 and 11-15 within the range 1 to 20, therefore it would have to return 1-2,9-10,16-20
CodePudding user response:
A fun way is to use set operations:
>>> r = set(range(1,21)) # numbers 1-20
>>> r
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
>>> q = set(range(3,9)) | set(range(11,16)) #numbers 3-8 and 11-15
>>> q
{3, 4, 5, 6, 7, 8, 11, 12, 13, 14}
>>> r-q # Difference of sets (elements in r that are not in q)
{1, 2, 9, 10, 15, 16, 17, 18, 19, 20}
CodePudding user response:
first, last = tuple(map(int, input("what are first and last numbers?").split(" ")))
data = set(range(first, last 1))
while True:
inp = input("entre set: ")
if inp == "":
break
first, last = tuple(map(int, inp.split(" ")))
numbers_set = set(range(first, last 1))
data -= numbers_set
data = tuple(data)
last_var = data[0]
res = str(data[0])
for var in data[1:]:
if var != last_var 1:
res = "-" str(last_var) ", " str(var)
last_var = var
res = "-" str(last_var)
print(res)