• [^] # Re: En Python, modélisé

    Posté par . En réponse au message Avent du Code, jour 9. Évalué à 2. Dernière modification le 09 décembre 2022 à 13:56.

    C'est pas tres joli non plus, mais on peut utiliser getattr/setattr pour factoriser la meme operation cote x et y dans la fonction de suivi:

    def get_closer(H: Point, T: Point, axis: str, aligned: bool) -> bool:
     diff = getattr(T, axis) - getattr(H, axis)
     if abs(diff) == 2:
     get_closer_by_1(H, T, axis)
     if not aligned:
     get_closer_by_1(H, T, "y" if axis == "x" else "x")
     return True
     return False
    def get_closer_by_1(H: Point, T: Point, axis):
     setattr(
     T, axis, getattr(T, axis) + (1 if getattr(H, axis) > getattr(T, axis) else -1)
     )
    def follow(H: Point, T: Point):
     aligned = T.x == H.x or T.y == H.y
     if not get_closer(H, T, "y", aligned):
     get_closer(H, T, "x", aligned)
    for input in inputs:
     for i in range(input[1]):
     match input[0]:
     case "U":
     H[0].y += 1
     case "L":
     H[0].x -= 1
     case "R":
     H[0].x += 1
     case "D":
     H[0].y -= 1
     for j in range(1, size_tail + 1):
     follow(H[j - 1], H[j])
     visited.add((H[size_tail].x, H[size_tail].y))

    Excusez l'absence d'accents dans mes commentaires, j'habite en Australie et n'ai pas de clavier francais sous la main.