85 lines
2.4 KiB
Python
85 lines
2.4 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
file = "./input.txt"
|
|
from copy import deepcopy
|
|
|
|
def sort_by_rules(update:list[int]) -> list[int]:
|
|
temp = (deepcopy(update))
|
|
is_not_sorted = True
|
|
while is_not_sorted:
|
|
is_not_sorted = False
|
|
for rule in rules:
|
|
if rule[0] not in temp or rule[1] not in temp:
|
|
continue
|
|
elif temp.index(rule[0]) > temp.index(rule[1]):
|
|
temp.pop(temp.index(rule[0]))
|
|
temp.insert(temp.index(rule[1]), rule[0])
|
|
is_not_sorted = True
|
|
return temp
|
|
|
|
def order_updates():
|
|
for update in updates_not_ok:
|
|
updates_not_ok_ordered.append(sort_by_rules(update))
|
|
|
|
def rules_ok(update:list[int]) -> bool:
|
|
for rule in rules:
|
|
if rule[0] not in update or rule[1] not in update:
|
|
continue
|
|
elif update.index(rule[0]) > update.index(rule[1]):
|
|
return False
|
|
return True
|
|
|
|
def check_updates():
|
|
for update in updates:
|
|
if rules_ok(update):
|
|
updates_ok.append(sort_by_rules(update))
|
|
else:
|
|
updates_not_ok.append(update)
|
|
|
|
|
|
def sum_middle_page_numbers_of_updates(update_list:list[list[int]]) -> int:
|
|
result = 0
|
|
for u in update_list:
|
|
result += u[len(u)//2]
|
|
return result
|
|
|
|
if __name__ == "__main__":
|
|
solution = 0
|
|
rules = []
|
|
updates = []
|
|
updates_ok = []
|
|
updates_not_ok = []
|
|
updates_not_ok_ordered = []
|
|
input_file = open(file, "r")
|
|
for line in input_file:
|
|
line = line.strip()
|
|
if line == "":
|
|
continue
|
|
elif "|" in line: # create a dictionary for rules
|
|
a, b = line.split("|")
|
|
rules.append([int(a), int(b)])
|
|
elif "," in line:
|
|
tmp = []
|
|
line = line.split(",")
|
|
for z in line:
|
|
tmp.append(int(z))
|
|
updates.append(tmp)
|
|
input_file.close()
|
|
|
|
check_updates()
|
|
order_updates()
|
|
|
|
print("Rules:")
|
|
print(rules)
|
|
print("Updates:")
|
|
print(updates)
|
|
print("\nPART 1")
|
|
print("OK-Updates")
|
|
print(updates_ok)
|
|
print(f'Solution-P1:{sum_middle_page_numbers_of_updates(updates_ok)}')
|
|
print("\nPART 2")
|
|
print("Not-OK-Updates")
|
|
print(updates_not_ok)
|
|
print("Not-OK-Updates Ordered")
|
|
print(updates_not_ok_ordered)
|
|
print(f'Solution-P2:{sum_middle_page_numbers_of_updates(updates_not_ok_ordered)}') |