48 lines
1.4 KiB
Python
48 lines
1.4 KiB
Python
|
def mid(values: list[str]):
|
||
|
return values[len(values)//2]
|
||
|
|
||
|
rules,updates = {}, []
|
||
|
with open('sample.data') as data:
|
||
|
for line in data:
|
||
|
if '|' in line:
|
||
|
left, right = [int(i) for i in line.split('|')]
|
||
|
if left in rules:
|
||
|
rules[left].append(right)
|
||
|
else:
|
||
|
rules[left] = [right]
|
||
|
if ',' in line:
|
||
|
updates.append([int(i) for i in line.split(',')])
|
||
|
|
||
|
def sort_updates(rules: dict[int, list[int]], updates: list) -> [list[int], list[int]]:
|
||
|
correct, incorrect = [], []
|
||
|
for update in updates:
|
||
|
for idx, val in enumerate(update):
|
||
|
fail = False
|
||
|
for after in update[idx:]:
|
||
|
if after == val:
|
||
|
continue
|
||
|
try:
|
||
|
if after not in rules[val]:
|
||
|
fail = True
|
||
|
incorrect.append(update)
|
||
|
break
|
||
|
except KeyError:
|
||
|
fail = True
|
||
|
incorrect.append(update)
|
||
|
break
|
||
|
if fail:
|
||
|
break
|
||
|
else:
|
||
|
# 75,47,61,53,29
|
||
|
# 97,61,53,29,13
|
||
|
# 75,29,13
|
||
|
print('good', update)
|
||
|
correct.append(mid(update))
|
||
|
return correct, incorrect
|
||
|
|
||
|
correct, incorrect = sort_updates(rules, updates)
|
||
|
print('COrrect', sum(correct))
|
||
|
print('incorrect', *incorrect)
|
||
|
|
||
|
|