[Advent of Code 2024](https://adventofcode.com/2024)
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

day05-1.py 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # The first section specifies the page ordering rules, one per line.
  2. # The first rule, 47|53, means that if an update includes both
  3. # page number 47 and page number 53, then page number 47 must be
  4. # printed at some point before page number 53. (47 doesn't necessarily
  5. # need to be immediately before 53; other pages are allowed to be
  6. # between them.)
  7. # The second section specifies the page numbers of each update.
  8. # Because most safety manuals are different, the pages needed in the
  9. # updates are different too. The first update, 75,47,61,53,29, means
  10. # that the update consists of page numbers 75, 47, 61, 53, and 29.
  11. def main051():
  12. with open("./input05.txt", "r", encoding="utf-8") as f:
  13. lines = [l.strip() for l in f.readlines()]
  14. rules = []
  15. updates = []
  16. for i, line in enumerate(lines):
  17. if "|" not in line:
  18. first_update = i + 1
  19. break
  20. rules.append([int(x) for x in line.split("|")])
  21. for i, line in enumerate(lines[first_update:]):
  22. updates.append([int(x) for x in line.split(",")])
  23. valid_updates = []
  24. total_vu = 0
  25. for u in updates:
  26. relevant_rules = [r for r in rules if all([x in u for x in r])]
  27. if all([u.index(rule[0]) < u.index(rule[1]) for rule in relevant_rules]):
  28. valid_updates.append(u)
  29. total_vu += u[(len(u)-1)//2]
  30. print(total_vu)
  31. if __name__ == "__main__":
  32. main051()