puzzle-01-02

mail@pastecode.io avatar
unknown
python
7 months ago
912 B
1
Indexable
Never
def main():
    with open("./input-day-01-02.txt", "r") as file:
        lines = file.readlines()
        lines = [line.strip() for line in lines]
        print(result(lines))

def result(lines):
    return sum(calibrate_number(line) for line in lines)

def calibrate_number(line):
    first = -1
    last = -1
    numbers = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]

    for i in range(len(line)):
        c = line[i]

        if c.isdigit():
            if first == -1:
                first = int(c)
            last = int(c)
            continue

        for number in numbers:
            if len(number) <= len(line[i:]) and number == line[i:i+len(number)]:
                num = numbers.index(number) + 1
                if first == -1:
                    first = num
                last = num

    return int(str(first) + str(last))

if __name__ == "__main__":
    main()
Leave a Comment