#Python

26 messages ยท Page 1 of 1 (latest)

glad pelican
#

Greedy felt too simple, but constructing from MSD means it is correct

#
def solve1(data: str) -> int:
    lines = [x for x in data.split('\n')]

    ans = 0
    for line in lines:
        best = 0
        for i in range(len(line) - 1):
            
            for j in range(i + 1, len(line)):
                best = max(best, int(line[i] + line[j]))
        ans += best

    return ans


def solve2(data: str) -> int:
    lines = [x for x in data.split('\n')]

    ans = 0

    for line in lines:
        pos = 0
        curr = ''

        while len(curr) < 12:
            val, where = max(((val, -i) for i, val in enumerate(line[pos:len(line)-(11 - len(curr))])))

            curr += val
            pos = pos - where + 1
        ans += int(curr)
        
    return ans
#

Got stuck for a bit on negative indexes not working right, had to switch from x[:-y] to x[:len(x)-y] which feels unintuitive

#

I don't think it can be really fixed though, x[:0] shouldn't return the whole list

#

Intuition for the list comp is "find the left most instance of the largest value in the remaining chars (leaving enough at the end to construct a number)"

glad pelican
#

@ebon coral day 3 thread ๐Ÿค

ebon coral
#
pickerino = 12

with open("03.txt") as f:
    lines = f.read().strip().split("\n")

out1 = 0
out2 = 0
for line in lines:
    digits = [int(c) for c in line]
    n = len(digits)

    dp = [[0] * (pickerino + 1) for _ in range(n + 1)]
    dp[n][0] = 0
    for i in range(n - 1, -1, -1):
        dp[i][0] = 0
        for length in range(1, pickerino + 1):
            take = 0 
            if i <= n - length:
                take = digits[i] * (10 ** (length - 1)) + dp[i + 1][length - 1]
            dp[i][length] = max(dp[i + 1][length], take)

    out1 += dp[0][2]
    out2 += dp[0][12]

print("part 1", out1)
print("part 2", out2)
ebon coral
glad pelican
#

they have the day tags on them

ebon coral
#

ok also i am a noob cuz i didn't add it to my channel list

#

so i didn't see the full forum view

glad pelican
glad pelican
ebon coral
#

sigh so slow debugging the edge cases

glad pelican
#

negative index slicing brought me pain

ebon coral
#

at first I had a bug where I didn't terminate for impossible cases (the if i <= n - length: line) so then like 1111...1119 would still have the wrong answer of 9000000...

ebon coral
dusty bronze
glad pelican
ebon coral
glad pelican
dusty bronze
ebon coral