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