Advent of Code 2022 day 13

There was quite a lot of faffing with part 1 for edge cases. The main edge case which caused issues is mitigated by the conditionals with the walrus operator, and the following code:

if type(a) == list and type(b) == list and len(a) == len(b):
    return None

Part 2 was fairly straightfoward. Used linear sort since it was effective enough.

# with open("13_test.txt") as f:
with open("13.txt") as f:
    pairs = [pair.splitlines() for pair in f.read().split("\n\n")]

def compare(a, b):
    for i, x in enumerate(a):
        if i >= len(b):
            return False
        elif type(x) == int and type(b[i]) == int and x > b[i]:
            return False
        elif type(x) == int and type(b[i]) == int and x < b[i]:
            return True
        elif type(x) == list and type(b[i]) == list:
            if (result := compare(x, b[i])) is not None:
                return result
        elif type(x) == int and type(b[i]) == list:
            if (result := compare([x], b[i])) is not None:
                return result
        elif type(x) == list and type(b[i]) == int:
            if (result := compare(x, [b[i]])) is not None:
                return result
    if type(a) == list and type(b) == list and len(a) == len(b):
        return None
    else:
        return True

print(
    sum(
        [i for i, (a, b) in enumerate(pairs, 1) if compare(eval(a), eval(b))]
    )
)

# part 2
signals = [x for pair in pairs for x in pair] + ["[[2]]", "[[6]]"]

def linear_sort(l):
    for i in range(len(l)):
        for j in range(i):
            if compare(eval(l[j]), eval(l[i])) is False:
                temp = l[i]
                l[i] = l[j]
                l[j] = temp
    return l

def product(l):
    mult = 1
    for x in l:
        mult *= x
    return mult

ordered = linear_sort(signals)
print(
    product([i for i, x in enumerate(ordered, 1) if x in ["[[2]]", "[[6]]"]])
)