Hallo Ich gab eine Reihe eindimensionaler Abschnitte und versuchte, ihre Überlappungen zu kombinieren. Siehe "Überlappende Intervalle zusammenführen" (Stapelüberlauf) und es ist fast dasselbe.
$ ./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