5-02
This commit is contained in:
39
05/05-2.py
Normal file
39
05/05-2.py
Normal file
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
import time
|
||||
|
||||
#file = "./ex.txt"
|
||||
file = "./input.txt"
|
||||
|
||||
def merge_intervals(intervals):
|
||||
if not intervals:
|
||||
return []
|
||||
intervals = sorted(intervals, key=lambda x: x[0])
|
||||
merged = [intervals[0]]
|
||||
for start, end in intervals[1:]:
|
||||
last_start, last_end = merged[-1]
|
||||
if start <= last_end:
|
||||
merged[-1] = (last_start, max(last_end, end))
|
||||
else:
|
||||
merged.append((start, end))
|
||||
return merged
|
||||
|
||||
if __name__ == "__main__":
|
||||
time_start = time.time()
|
||||
solution = 0
|
||||
fresh_ranges = []
|
||||
input_file = open(file, "r")
|
||||
for line in input_file:
|
||||
line = line.strip()
|
||||
if line == "" or "-" not in line:
|
||||
continue
|
||||
else:
|
||||
a,b = line.split('-')
|
||||
a = int(a)
|
||||
b = int(b)
|
||||
fresh_ranges.append([a,b])
|
||||
id_set = set()
|
||||
merged_ranges = merge_intervals(fresh_ranges)
|
||||
for start, end in merged_ranges:
|
||||
solution += (end - start + 1)
|
||||
print(f"Solution: {solution} benötigte Zeit = {time.time()-time_start} s")
|
||||
Reference in New Issue
Block a user