58 lines
1.2 KiB
Python
58 lines
1.2 KiB
Python
from typing import Generator
|
|
|
|
|
|
def parse_input() -> list[tuple[int, int]]:
|
|
with open("input.txt", "r") as f:
|
|
output = []
|
|
for case in f.read().split(","):
|
|
n1, n2 = map(int, case.split("-"))
|
|
output.append((n1, n2))
|
|
return output
|
|
|
|
|
|
def part_1():
|
|
total = 0
|
|
for n1, n2 in parse_input():
|
|
for n in range(n1, n2 + 1):
|
|
n_str = str(n)
|
|
middle = len(n_str) // 2
|
|
if len(n_str) % 2 == 0 and len(set(n_str)) == 1:
|
|
total += n
|
|
elif n_str[:middle] == n_str[middle:]:
|
|
total += n
|
|
print(total)
|
|
|
|
|
|
def wrap(s: str, n: int) -> Generator[str]:
|
|
while s:
|
|
yield s[:n]
|
|
s = s[n:]
|
|
|
|
|
|
def part_2():
|
|
total = 0
|
|
for n1, n2 in parse_input():
|
|
for n in range(n1, n2 + 1):
|
|
n_str = str(n)
|
|
len_n = len(n_str)
|
|
middle = len_n // 2
|
|
for div in range(1, middle + 1):
|
|
if len_n % div != 0:
|
|
continue
|
|
|
|
if len(set(wrap(n_str, div))) == 1:
|
|
total += n
|
|
break
|
|
print(total)
|
|
|
|
|
|
def main():
|
|
print("Part 1:")
|
|
part_1()
|
|
print("Part 2:")
|
|
part_2()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|