Bonjour J'ai donné un ensemble de sections unidimensionnelles et essayé de combiner leurs chevauchements. Reportez-vous à «fusion d'intervalles qui se chevauchent» (Stack Overflow) et c'est presque la même chose.
$ ./merger.py
input: [[-25, -14], [-21, -16], [-20, -15], [-10, -7], [-8, -5], [-6, -3], [2, 4], [2, 3], [3, 6], [12, 15], [13, 18], [14, 17], [22, 27], [25, 30], [26, 29]]
output: [[-25, -14], [-10, -3], [2, 6], [12, 18], [22, 30]]
merger.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def merger(intervals):
intervals.sort(key=lambda interval: interval[0])
merged = [intervals[0]]
for w in intervals:
if w[0] > merged[-1][1]:
merged.append(w)
elif w[1] > merged[-1][1]:
merged[-1][1] = w[1]
return merged
intervals = [[-25, -14], [-21, -16], [-20, -15], [-10, -7], [-8, -5], [-6, -3], [2, 4], [2, 3], [3, 6], [12, 15], [13, 18], [14, 17], [22, 27], [25, 30], [26, 29]]
print(f"input: {intervals}")
print(f"output: {merger(intervals)}")
Recommended Posts