Assigning an element of a list to another (Python)

Viewed 77

I am trying to find help assigning an element of a list to another. To be specific, I am doing the "Sum of Intervals" challenge on Codewars.

Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once.

Intervals

Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4.

Overlapping Intervals

List containing overlapping intervals:

[
  [1,4],
  [7, 10],
  [3, 5]
]

The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4.

I am confused as to why trying to assign an element of a list to another fails. Here is my code:

def sum_of_intervals(intervals):
    sum = 0
    for thing in intervals:
        thing = list(thing)
        for thing2 in intervals:
            thing2 = list(thing2)
            if thing[1] > thing2[0] and thing[1] < thing2[1]:
                if thing == thing2 and intervals.index(thing) != intervals.index(thing2):
                    intervals.remove(tuple(thing2))
                else:
                    thing[1] = thing2[1] #line that does not seem to be working
                    intervals.remove(tuple(thing2))
    for thing3 in intervals:
        sum += thing[1] - thing[0]
    return sum

Does anyone know why thing[1] = thing2[2] does not work? If I return intervals instead of sum, for example for ([(1,5),(3,7)]) it just returns (1, 5) or sum of 4.

If this question has been asked before (which it does not look like it has) please tell me and guide me there. Thank you!

1 Answers

The fact that the intervals contain only integers is a gross simplification of the task. It can be solved in one line:

sum_of_intervals = lambda x: len(set.union(*[set(list(range(*i))) for i in x]))
Related