Sergio Robert
Sergio Robert

Reputation: 15

list index out of range Django overlapping

Hi When I am checking overalapping i am getting list index out of range, how i can solve that ,

 for i in range(count):
        start_value=(self.data.get(f'applicationvalue_set-{i}-start_value', []))
        end_value=(self.data.get(f'applicationvalue_set-{i}-end_value', []))
        if start_value is not None or end_value is not None:
            value1=[]
            value2=[]
            for start in start_value:
                if start not in value1:
                    value1.append(start)
            for end in end_value:
                if end not in value2:
                    value2.append(end)
            a=range(value1[0],value1[-1])

            b=range(value2[0],value2[-1])
            if a in b.exists():
                 raise ValidationError("overlap not allowed")djangp

Upvotes: 0

Views: 73

Answers (1)

ruddra
ruddra

Reputation: 51948

I don't see the reason for so many lines of code where you can simply solve it with set():

 start_value=set(self.data.get(f'applicationvalue_set-{i}-start_value', []))
 end_value= set(self.data.get(f'applicationvalue_set-{i}-end_value', []))
 
 if end_value.intersection(start_value):
     raise ValidationError("overlap not allowed")

Here I converting the list into set, as set datatype contains only unique data, and I can run intersection between two sets. More information can be found here: https://docs.python.org/3/tutorial/datastructures.html#sets

Alternative

You can consider minimum of end_value to be bigger than maximum of start_value:

if min(end_value) < max(start_value):
    raise ValidationError("overlap not allowed")

Alternative 2

I am not sure if you should use set it will mess up the sequence of the input from the user (as set remove any duplicates). If its not an issue, then you can use the following code:

prev = None

for x in zip(start_value, end_value):
    if prev and x[0] < prev[1]:
        raise ValidationError("...")
    prev = x

Here zip will return a tuple of items combining from start and end value.

Upvotes: 1

Related Questions