◂ 4 décembre 2022 ▸
Camp Cleanup : Intersection de zones-intervalles
34-82,33-81
59-59,69-73
6-96,98-99
1-94,3-96
13-92,20-64
⋮
- code.py
import re
f = open("input.txt", 'r')
lines = [line.strip() for line in f.readlines()]
##### FAÇON (1) AVEC COMPARAISON DES BORNES :
nbPartie1 = 0
nbPartie2 = 0
for line in lines:
# Découper a1-a2,b1-b2 :
[a1,a2, b1,b2] = map(int, re.split('[^0-9]', line))
if ((a1 >= b1) and (a2 <= b2)) or ((a1 <= b1) and (a2 >= b2)):
nbPartie1 += 1
if ((a2 >= b1) and (a1 <= b2)) or ((a2 <= b1) and (a1 >= b2)):
nbPartie2 += 1
print("Réponse partie 1:", nbPartie1)
print("Réponse partie 2:", nbPartie2)
##### FAÇON (2) AVEC DES ENSEMBLES :
nbPartie1 = 0
nbPartie2 = 0
for line in lines:
# Découper a1-a2,b1-b2 :
[a1,a2, b1,b2] = map(int, re.split('[^0-9]', line))
sectionsA = set(range(a1, a2+1))
sectionsB = set(range(b1, b2+1))
if sectionsA.issubset(sectionsB) or sectionsA.issuperset(sectionsB):
nbPartie1 += 1
if not sectionsA.isdisjoint(sectionsB): # len(sectionsA.intersection(sectionsB)) > 0
nbPartie2 += 1
print("Réponse partie 1:", nbPartie1)
print("Réponse partie 2:", nbPartie2)
## Alternative pour (1) sans regexp, ni map :
# [a, b] = line.split(',')
# [a1, a2] = a.split('-')
# [b1, b2] = b.split('-')
# a1 = int(a1)
# a2 = int(a2)
# b1 = int(b1)
# b2 = int(b2)