How to delete a range of values from a list and make the aforementioned subtracted range unavailable in a new list?

Viewed 141

I am wondering if it is possible to create a function to subtract a range of values from a list, and a new list be created in which the aforementioned range of values that was subtracted are now "unavailable". I will put my thinking below in iterations:

I have my initial list with values that range from 0 to 1000 by 1, so lista = [*range(0,1001)].

First iteration

lista = [*range(0,1001)]

Second iteration

I subtract [*range(450,602)] from lista

New ranges available 301 to 449 and 602 to 1000

Third iteration

I subtract [*range(700,800)] from lista

New ranges available: 301 to 449, 602 to 699, 801 to 1000

So now if I wanted to subtract [*range(430,501)] from lista it would be "unavailable" because it overlaps a now "unavailable" range. However, [*range(650,671)] would be "available".

I know I can subtract a range of values using set() with something like, list(set(lista)-set(newRange))), however, my issue is how identify the previous subtracted ranges, or values within those subtracted ranges, as being "unavailable".

1 Answers

IIUC, how about this?

def range_subtraction(ls, low, hi):
    if len(set(range(low, hi)) - set(ls)):
        raise Exception('Unavailable range.')
    else:
        return list(set(ls) - set(range(low,hi)))

If there are range values outside the input, then throw an error. Otherwise, do the set subtraction you mentioned.

So if you do the following, a works but b throws the Exception:

a = range_subtraction(lista, 450, 602)
b = range_subtraction(a, 430, 501)
Related