◂ 15 décembre 2023 ▸
Lens Library : Suivre des instructions pour placer des lentilles dans des boites et changer leur distance focale
dcf=3,hp=9,kjfhxf-,hpmvrg-,pnb=7,zxz-,vrmt=4,ghrx=7,fz-, …
- code_avec_classe.py
- code_avec_classe_hashmap.py
- code_sans_classe.py
from functools import reduce
Lentille = tuple[str, int]
Box = list[Lentille]
class HashmapFocales():
__slots__ = ['__boxes']
# Attributs d'instance
__boxes: list[Box]
@classmethod
def hash(cls, the_string: str) -> int:
return reduce(lambda h,char: (h + ord(char)) * 17 % 256, the_string, 0)
def __init__(self) -> None:
self.__boxes: list[Box] = [ [] for _ in range(256) ]
def get_focale(self, nom: str) -> int|None:
h = self.hash(nom)
for (k, focale) in self.__boxes[h]:
if k == nom:
return focale
return None
# Permet un accès de type focale = lentilles[nom]
def __getitem__(self, nom: str) -> None|int:
return self.get_focale(nom)
def set_focale(self, nom, focale) -> None:
h = self.hash(nom)
for i,(k,_) in enumerate(self.__boxes[h]):
if k == nom:
self.__boxes[h][i] = (nom, focale)
return
self.__boxes[h].append( (nom, focale) )
# Permet un accès de type lentilles[nom] = focale
def __setitem__(self, nom: str, focale: int) -> None:
return self.set_focale(nom, focale)
def pop(self, nom) -> int|None:
h = self.hash(nom)
for i,(k, focale) in enumerate(self.__boxes[h]):
if k == nom:
self.__boxes[h].pop(i)
return focale
return None
# pas d'exception si pas trouvé
def total_focusing_power(self) -> int:
return sum( (iBox + 1) * (iLentille + 1) * focale
for iBox, box in enumerate(self.__boxes)
for iLentille, (nom, focale) in enumerate(box))
instructions = open('input.txt', 'r', encoding='utf-8').read().strip().split(',')
reponse_partie_1 = sum(map(HashmapFocales.hash, instructions))
lentilles = HashmapFocales()
for instruction in instructions:
if instruction.endswith('-'):
nom = instruction[:-1]
lentilles.pop(nom)
else:
nom, chiffre = instruction.split('=')
lentilles[nom] = int(chiffre)
print("Réponse partie 1:", reponse_partie_1)
print("Réponse partie 2:", lentilles.total_focusing_power())