""" advent9.py advent of code day 9 """ import re def dump_exclamation(stream): """ Remove !. from stream. Return new version >>> dump_exclamation('!!abc!abbb') 'abcbbb' >>> dump_exclamation('--!a!!!b,') '--,' >>> dump_exclamation('{{},{},{},{}}') '{{<},{<},{<},{}}' """ return re.sub(r'!.', '', stream) def dump_angles(stream): """ Remove <....> from stream; return new version. >>> dump_angles('a<<<<>b') 'ab' >>> dump_angles('<>') '' >>> dump_angles('ab]*>', '', stream) def angles_to_dashes(stream): """ count number of garbage characters >>> len('<>') - len(angles_to_dashes('<>')) 0 >>> len('<<<<>') - len(angles_to_dashes('<<<<>')) 3 """ return re.sub(r'<[^>]*>', '--', stream) # test regular expression in python : # print re.sub(r'^(.*)(ab)(cd)(.*)$', # r'\1\3\2\4', "__abcde__") def score_groups(stream): """ Return score for embedded curlies >>> score_groups('{}') 1 >>> score_groups('{{{}}}') 6 >>> score_groups('{{},{}}') 5 >>> score_groups('{{{},{},{{}}}}') 16 """ depth = 0 total = 0 for ch in stream: if ch == '{': depth = depth + 1 if ch == '}': total = total + depth depth = depth - 1 return total def remove_exclaims(stream): result = '' last_was_exclaim = False for i in range(len(stream)): if last_was_exclaim: last_was_exclaim = False elif stream[i] == '!': last_was_exclaim = True else: result = result + stream[i] return result def main(): data = open("day9_input.txt").read() data_dumped = dump_exclamation(data) data_dump_squared = dump_angles(data_dumped) score = score_groups(data_dump_squared) print "answer to part 1 is ", score # length1 = len(data_dumped) length2 = len(angles_to_dashes(data_dumped)) print "answer to part 2 is ", length1 - length2 if __name__ == "__main__": import doctest doctest.testmod() main()