-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp18a.py
119 lines (108 loc) · 2.52 KB
/
p18a.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# https://adventofcode.com/2021/day/18 part 1
# Created by: Menaka S. 18 Dec 2021
import sys
from ast import literal_eval
import copy
import math
import re
mylist = []
mystr = ''
first = 1
def is_other_char(char):
if char in ('[',']',','):
return 1
return 0
def parseinp(text):
if text and is_other_char(text[0]):
mylist.append(text[0])
parseinp(text[1:])
else:
mtext = re.match(r"^(\d+)",text)
if mtext:
mylist.append(int(mtext[0]))
parseinp(text[len(mtext[0]):])
def mysplit():
global mylist
newlist = []
alreadysplit = 0
for i in range(len(mylist)):
if is_other_char(mylist[i]):
newlist.append(mylist[i])
elif mylist[i] < 10:
newlist.append(mylist[i])
else:
if not alreadysplit:
#print(mylist[i],"splitting")
newlist.extend(['[',math.floor(mylist[i]/2),',',math.ceil(mylist[i]/2),']'])
alreadysplit = 1
else:
newlist.append(mylist[i])
mylist = copy.deepcopy(newlist)
#print(''.join(str(e) for e in mylist))
def myreduce(level,ind):
global mylist
while( ind < len(mylist)):
if mylist[ind] == '[':
level += 1
if mylist[ind] == ']':
level -= 1
if level >= 5:
needsplit = 0
lhs = mylist[ind+1]
rhs = mylist[ind+3]
j = ind
#print(lhs,rhs)
while j >=0:
if isinstance(mylist[j],int):
#print(lhs,"lll")
mylist[j] += lhs
break
j -=1
j = ind+4
while j < len(mylist):
if isinstance(mylist[j],int):
#print(rhs,"rrrr")
mylist[j] += rhs
break
j +=1
mylist = mylist[:ind] +[0] + mylist[ind+5:]
#print(''.join(str(e) for e in mylist))
level -=1
ind +=1
def getmagnitude(lst):
#print(lst)
if isinstance(lst[0],int) and isinstance(lst[1],int):
return (3 * lst[0]) + (2 * lst[1])
elif isinstance(lst[0],list) and isinstance(lst[1],int):
return (3 * getmagnitude(lst[0])) + (2 * lst[1])
elif isinstance(lst[0],int) and isinstance(lst[1],list):
return (3 * lst[0]) + (2 * getmagnitude(lst[1]))
else:
return (3 * getmagnitude(lst[0])) + (2 * getmagnitude(lst[1]))
for line in sys.stdin:
line = line.strip()
if first:
mystr = line
first = 0
parseinp(mystr)
else:
mylist.insert(0,'[')
mylist.append(',')
parseinp(line)
mylist.append(']')
#print("Added")
#print(''.join(str(e) for e in mylist))
while True:
oldlist = copy.deepcopy(mylist)
myreduce(0,0)
mysplit()
if mylist == oldlist:
break
#print(''.join(str(e) for e in mylist))
mlist = literal_eval(''.join(str(e) for e in mylist))
#print(mlist)
if len(mlist) == 1:
mlist = mlist[0]
#print("Mgni")
mag = getmagnitude(mlist)
print(mag)