Yekong's Blog

A blog about my experiences and thoughts.

Description

Part 1: Just do a simple data processing. Part 2: Also do a data processing, but with a rule.

123 328  51 64
 45 64  387 23
  6 98  215 314
*   +   *   +

You need to read it from right to left, and top to bottom. Example: xx4, 431, 623

Code

with open("input", "r") as f:
    content = f.read().strip().split("\n")

    content_pos = 0
    for i in content:
        content_pos = max(len(i), content_pos)

    total = 0
    numbers = []
    operator = ""
    flag = False
    while content_pos >= 0:
        number = ""
        for i in content:
            try:
                if i[content_pos] != " " and i[content_pos].isdigit():
                    number += i[content_pos]
                elif i[content_pos] == "+":
                    operator = "+"
                    flag = True
                elif i[content_pos] == "*":
                    operator = "*"
                    flag = True
            except IndexError:
                pass
        if number:
            numbers.append(int(number))
        number = ""
        content_pos -= 1

        if flag:
            if operator == "+":
                for i in numbers:
                    total += i
            elif operator == "*":
                tmp = 1
                for i in numbers:
                    tmp *= i
                total += tmp
            numbers = []
            flag = False

    print(total)