2016-12-09 Advent of Code in Python
It was pretty easy to slide back into Python. I used Python 3 because I hear thatβs what one ought to use. I really like the Python documentation. A very good read. You can tell because I prefer reading the documentation to searching for examples on StackExchange. Well done!
So, Advent of Code, day 7, part 1: Count how many strings comply with the following specification:
1. Each string consists of some letters, with one or more sections in square brackets, e.g. `alex[berta]otto`.
2. The string must have a four character palindrome consisting of two different letters *outside* square brackets, e.g. `otto` in the example above.
3. No such string may be found withing square brackets.
4. There may be multiple sets of square brackets within the string.import sys import redef has_palindrome(word): m = re.search(r"([a-z])([a-z])\2\1", word) # aaaa is not a valid palindrome if (m and m.group(1) != m.group(2)): return 1def check_line(line): inside = 0 outside = 0 parts = re.findall('([a-z]+)(?:[([a-z]+)])?', line) for part in parts: if (has_palindrome(part[0])): outside += 1 if (has_palindrome(part[1])): inside += 1 return inside == 0 and outside > 0def check_input(): sum = 0 for line in sys.stdin: if check_line(line): sum += 1 return sumif **name** == '**main**': print (str(check_input()))
Part 2: Count how many strings comply with the following specification:
1. Each string consists of some letters, with one or more sections in square brackets, e.g. `ala[lala]otto`.
2. The string must have a three character palindrome consisting of two different letters *outside* square brackets, e.g. `ala`, and a matching inverted three character palindrome *inside* any of the square brackets, e.g. `lal` in the example above.
3. There may be multiple sets of square brackets within the string.
This was surprisingly more difficult!
Call using `python part1.py < data` and `python part2.py < data`.
I also wondered about an integrated Python debugger for Emacs. Sadly, I used print statements all over the place as I was searching for bugs.
β#Python β#Advent of Code β#Programming
Comments
(Please contact me if you want to remove your comment.)
β
You can use the fileinput module for reading the data: https://docs.python.org/2/library/fileinput.html
https://docs.python.org/2/library/fileinput.html
Instead of for i in range(len(word) - 2): you can do something like for a, b, c in zip(word, word[1:], word[2:]):
Instead of re.search you can simply use the βinβ operator.
β Radomir Dopieralski 2016-12-09 08:23 UTC
---
Thanks!
β AlexSchroeder 2016-12-09 11:40 UTC