Skip to content

Instantly share code, notes, and snippets.

@jsbueno
Created December 14, 2022 03:15
Show Gist options
  • Save jsbueno/415fc72284c267d6dc272441134a9280 to your computer and use it in GitHub Desktop.
Save jsbueno/415fc72284c267d6dc272441134a9280 to your computer and use it in GitHub Desktop.
"""
SPOILER ALERT!
Problem at: https://adventofcode.com/2022/day/13
This one was made quite easy by using Python's native comparison heuristics
along with operator overloading.
Part 2 was ready without a single new line of code on the class- just adding the markers,
and applying "sorted" and the ".index" method on the data
"""
class Day13List:
def __init__(self, data):
data = data.strip()
if data.isdigit():
self.value = int(data)
self.data = None
else:
self.value = None
self.parse(data)
def parse(self, data):
cls = type(self)
if data[0] != "[":
raise ValueError()
start0 = 0
counter = 1
tokens = []
inner_num = inner_list = ""
for char in data[1:]:
if char == "[":
counter += 1
inner_list += char
elif char == "]":
if inner_num:
tokens.append(cls(inner_num))
inner_num = ""
counter -= 1
if counter == 0:
break
elif counter == 1:
tokens.append(cls(inner_list + "]"))
inner_list = ""
else:
inner_list += char
elif inner_list:
inner_list += char
elif char == ",":
if inner_num:
tokens.append(cls(inner_num))
inner_num = ""
else:
#asublist had been added when its bracked closed
pass
elif char.isdigit():
inner_num += char
self.data = tokens
def wrap(self):
if self.data is not None:
return self
cls = type(self)
instance = cls.__new__(cls)
instance.value = None
instance.data = [self]
return instance
def _cmp(self, other, op):
if self.value is not None and other.value is not None:
return op(self.value, other.value)
x = self.wrap()
y = other.wrap()
return op(x.data, y.data)
def __eq__(self, other):
return self._cmp(other, eq)
def __lt__(self, other):
return self._cmp(other, lt)
def __repr__(self):
if self.value is not None:
return str(self.value)
return "[" + ", ".join(repr(item) for item in self.data) + "]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment