Solution to problem 9 in Python

This commit is contained in:
David Doblas Jiménez 2022-04-23 18:27:09 +02:00
parent 131a7afee7
commit 8a4be14c2c

View File

@ -63,5 +63,56 @@ def part_1() -> None:
print(f"The length of the file is {ans}")
# --- Part Two ---
# Apparently, the file actually uses version two of the format.
# In version two, the only difference is that markers within decompressed data
# are decompressed. This, the documentation explains, provides much more
# substantial compression capabilities, allowing many-gigabyte files to be
# stored in only a few kilobytes.
# For example:
# (3x3)XYZ still becomes XYZXYZXYZ, as the decompressed section contains no
# markers.
# X(8x2)(3x3)ABCY becomes XABCABCABCABCABCABCY, because the decompressed
# data from the (8x2) marker is then further decompressed, thus triggering the
# (3x3) marker twice for a total of six ABC sequences.
# (27x12)(20x12)(13x14)(7x10)(1x12)A decompresses into a string of A
# repeated 241920 times.
# (25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN becomes 445
# characters long.
# Unfortunately, the computer you brought probably doesn't have enough memory
# to actually decompress the file; you'll have to come up with another way to
# get its decompressed length.
# What is the decompressed length of the file using this improved format?
def improved_rec_decompression(my_str: str) -> int:
marker = re.search(r"\(\d+x\d+\)", my_str)
if not marker:
return len(my_str)
else:
match_numbers = re.findall(r"\d+", marker.group())
chars_to_repeat, times = (int(n) for n in match_numbers)
start, end = marker.start(), marker.end()
return (
len(my_str[:start])
+ times
* improved_rec_decompression(my_str[end : end + chars_to_repeat])
+ improved_rec_decompression(my_str[end + chars_to_repeat :])
)
def part_2() -> None:
ans = improved_rec_decompression(chars[0])
print(f"The length of the file is {ans}")
if __name__ == "__main__":
part_1()
part_2()