Avent of Code-第13天 - 遇险信号
#编程 #python #adventofcode #blog

Advent of Code发生在12月01日至25日,每天您需要解决一个难题。这是节日,问题声明主要与圣诞节有关。

第13天 - 遇险信号

https://adventofcode.com/2022/day/13

image.png

Q1

import sys
from collections import defaultdict, deque

file1 = open(sys.argv[1], "r")

ans = 0

def check(a, b):
    if a < b:
        return "yes"
    if a > b:
        return "no"

def f(a, b):
    ans = False
    for p in zip(a, b):
        if type(p[0]) == type(p[1]) == int:
            ans = check(p[0], p[1])
        elif type(p[0]) == type(p[1]) == type([]):
            ans = f(p[0], p[1])
        elif type(p[0]) == int and type(p[1]) == type([]):
            ans = f([p[0]], p[1])
        elif type(p[0]) == type([]) and type(p[1]) == int:
            ans = f(p[0], [p[1]])
        if ans:
            break
    if not ans:
        if len(a) < len(b):
            return "yes"
        elif len(a) > len(b):
            return "no"
    return ans

cur = []
data = []
while True:
    line = file1.readline()
    if not line:
        break
    line = line.strip()
    if not line:
        data.append(cur[:])
        cur = []
        continue
    cur.append(eval(line))

if len(cur) == 2:
    data.append(cur[:])

for i, (a, b) in enumerate(data):
    print(a, b)
    if f(a, b) == "yes":
        ans += i + 1
        print(i + 1)

print(ans)

Q2

from functools import cmp_to_key
import sys
from collections import defaultdict, deque

file1 = open(sys.argv[1], "r")

ans = 0

def check(a, b):
    if a < b:
        return -1
    if a > b:
        return 1
    return 0

def f(a, b):
    ans = False
    for p in zip(a, b):
        if type(p[0]) == type(p[1]) == int:
            ans = check(p[0], p[1])
        elif type(p[0]) == type(p[1]) == type([]):
            ans = f(p[0], p[1])
        elif type(p[0]) == int and type(p[1]) == type([]):
            ans = f([p[0]], p[1])
        elif type(p[0]) == type([]) and type(p[1]) == int:
            ans = f(p[0], [p[1]])
        if ans:
            break
    if not ans:
        if len(a) < len(b):
            return -1
        elif len(a) > len(b):
            return 1
    return ans

data = []
while True:
    line = file1.readline()
    if not line:
        break
    line = line.strip()
    if line:
        data.append(eval(line))

a=[[2]]
b=[[6]]
data.extend([a, b])

data.sort(key=cmp_to_key(f))
for x in data:
    print(x)
print((data.index(a) + 1) * (data.index(b) + 1))

技巧:使用eval简化对混合数组/整数类型的解析输入(多维数组)。
端子值
Q2由CMP_TO_KEY分类。


Steem到月球!