Solve 2016 day 9.
This commit is contained in:
46
2016/d9.py
Normal file
46
2016/d9.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from lib import *
|
||||
|
||||
data = open(0).read().strip()
|
||||
|
||||
def count_non_rec(data):
|
||||
text = ""
|
||||
i = 0
|
||||
while i < len(data):
|
||||
if data[i] == "(":
|
||||
for j in range(i + 1, len(data)):
|
||||
if data[j] == ")":
|
||||
break
|
||||
else:
|
||||
assert False
|
||||
length, repeats = str_to_ints(data[i:j])
|
||||
to_repeat = data[j + 1: j + 1 + length]
|
||||
text += (to_repeat * repeats)
|
||||
i = (j + length + 1)
|
||||
else:
|
||||
text += data[i]
|
||||
i += 1
|
||||
return len(text)
|
||||
|
||||
def count(data):
|
||||
if not "(" in data:
|
||||
return len(data)
|
||||
r = 0
|
||||
i = 0
|
||||
while i < len(data) and data[i] != "(":
|
||||
i += 1
|
||||
r += 1
|
||||
|
||||
if data[i] == "(":
|
||||
for j in range(i + 1, len(data)):
|
||||
if data[j] == ")":
|
||||
break
|
||||
else:
|
||||
raise Exception("No matching ) found!")
|
||||
length, repeats = str_to_ints(data[i:j])
|
||||
r += (count(data[j + 1:j + 1 + length]) * repeats)
|
||||
r += count(data[j + 1 + length:])
|
||||
return r
|
||||
|
||||
|
||||
print(count_non_rec(data))
|
||||
print(count(data))
|
||||
Reference in New Issue
Block a user