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:
def sum_of_intervals(intervals):
data = {}
new = []
new_add = []
mmax = []
sum = 0
intervals = sorted(intervals)
print(intervals)
for i in intervals:
cc = i[1] - i[0]
mmax.append(cc)
for j in range(len(intervals)):
if intervals[j][0] == i[0]:
if intervals[j][1] < i[1]:
if intervals[j] not in new:
new.append(intervals[j])
if intervals[j][1] == i[1]:
if intervals[j][0] > i[0]:
if intervals[j] not in new:
new.append(intervals[j])
if intervals[j][0] < i[0] and intervals[j][1] > i[1]:
if i not in new:
new.append(i)
if i[0] < intervals[j][0] <= i[1] and intervals[j][1] > i[1]:
if [i[0], intervals[j][1]] not in new_add:
new_add.append([i[0], intervals[j][1]])
if intervals[j] not in new:
new.append(intervals[j])
if i not in new:
new.append(i)
max_kuadu = intervals[mmax.index(max(mmax))]
print('最大跨度的数', max_kuadu)
if new:
for i in new:
intervals.pop(intervals.index(i))
intervals.extend(new_add)
if intervals:
for i in intervals:
data[i[0]] = 'START'
data[i[1]] = 'ESC'
xuhao = sorted(data.items())
print('第一次清洗后的xuhao', xuhao)
for c in xuhao:
if max_kuadu[0] < c[0] < max_kuadu[1]:
xuhao.remove(c)
print('第二次清洗后的列表', xuhao)
for i in range(len(xuhao)):
tiaojian = xuhao[i][1]
if tiaojian == 'START':
if xuhao[i + 1][1] == 'START':
sum += xuhao[i + 1][0] - xuhao[i][0]
print('%s - %s = %s 第一次' % (xuhao[i + 1][0], xuhao[i][0], sum))
else:
pass
else:
if tiaojian == 'ESC':
sum += xuhao[i][0] - xuhao[i - 1][0]
print('%s - %s = %s 第三次' % (xuhao[i][0], xuhao[i - 1][0], sum))
if i+1 < len(xuhao):
if xuhao[i + 1][1] == 'START':
print(xuhao[i][0])
for jj in intervals:
if jj[0] < xuhao[i][0] < jj[1]:
print('jj,.',jj,xuhao[i][0])
sum += xuhao[i+1][0] - xuhao[i][0]
print('%s - %s = %s 第二次' % (xuhao[i+1][0], xuhao[i][0], sum))
break
return sum
精简吧…
def sum_of_intervals(intervals):
s, top = 0, float("-inf")
for a,b in sorted(intervals):
if top < a: top = a
if top < b: s, top = s+b-top, b
return s