• [^] # Re: python, en trichant

    Posté par (Mastodon) . En réponse au message Avent du Code, jour 13. Évalué à 2.

    J'ai un code équivalent, avec un peu plus de modélisation, mais sinon, c'est algorithmiquement identique :

    import sys
    import json
    from functools import total_ordering
    @total_ordering
    class packet:
     def __init__(self, data):
     self.data = data
     def compare(self, a, b):
     if type(a) == type(b) == int:
     if a == b:
     return None
     return a < b
     if type(a) == int:
     a = [a]
     if type(b) == int:
     b = [b]
     for i, j in zip(a, b):
     c = self.compare(i, j)
     if c is not None:
     return c
     else:
     return self.compare(len(a), len(b))
     return None
     def __lt__(self, other):
     return self.compare(self.data, other.data) is True
     def __eq__(self, other):
     return self.compare(self.data, other.data) is None
    def input():
     x = None
     for line in sys.stdin:
     if line == "\n":
     x = None
     elif x is not None:
     yield x, packet(json.loads(line))
     else:
     x = packet(json.loads(line))
    score = 0
    all_packets = []
    for id, (a, b) in enumerate(input()):
     all_packets += [a, b]
     if a <= b:
     score += id + 1
    print(f"Pairs in the right order : {score}")
    decoder = [packet([[2]]), packet([[6]])]
    s = sorted(all_packets + decoder)
    print(f"Decoder Key = {(s.index(decoder[0])+1) * (s.index(decoder[1])+1)}")

    Je n'ai pas songé à split("\n\n"), ça fait que j'ai une première partie qui bosse en flux, mais comme pour la seconde il faut trier, on est obligé d'avoir toutes les données chargées, change rien.
    Et ma fonction de comparaison est très centrée sur l'exercice : a < b c'est True, a > b c'est False et a == b c'est None, ergo on poursuit. C'est plus propre de faire -1/0/1.

    • Yth.