My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add starter.py and utils.py for 2019

+251
+32
2019/starter.py
··· 1 + import os # NOQA 2 + import sys # NOQA 3 + import re # NOQA 4 + import math # NOQA 5 + import fileinput 6 + from string import ascii_uppercase, ascii_lowercase # NOQA 7 + from collections import Counter, defaultdict, deque, namedtuple # NOQA 8 + from itertools import count, product, permutations, combinations, combinations_with_replacement # NOQA 9 + 10 + from utils import parse_line, parse_nums, mul, all_unique, factors, memoize, primes # NOQA 11 + from utils import new_table, transposed, rotated # NOQA 12 + from utils import md5, sha256, knot_hash # NOQA 13 + from utils import VOWELS, CONSONANTS # NOQA 14 + from utils import Point, DIRS, DIRS_4, DIRS_8 # NOQA 15 + 16 + # Itertools Functions: 17 + # product('ABCD', repeat=2) AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD 18 + # permutations('ABCD', 2) AB AC AD BA BC BD CA CB CD DA DB DC 19 + # combinations('ABCD', 2) AB AC AD BC BD CD 20 + # combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC BD CC CD DD 21 + 22 + total = 0 23 + result = [] 24 + table = new_table(None, width=2, height=4) 25 + 26 + for i, line in enumerate(fileinput.input()): 27 + line = line.strip() 28 + nums = parse_nums(line) 29 + data = parse_line(r'', line) 30 + 31 + if i == 0: 32 + print(data)
+219
2019/utils.py
··· 1 + import re 2 + import math 3 + import hashlib 4 + import operator 5 + from functools import total_ordering 6 + 7 + 8 + LETTERS = [x for x in 'abcdefghijklmnopqrstuvwxyz'] 9 + VOWELS = {'a', 'e', 'i', 'o', 'u'} 10 + CONSONANTS = set(x for x in LETTERS if x not in VOWELS) 11 + 12 + 13 + def parse_line(regex, line): 14 + ret = [] 15 + for match in re.match(regex, line).groups(): 16 + try: 17 + ret.append(int(match)) 18 + except ValueError: 19 + ret.append(match) 20 + 21 + return ret 22 + 23 + 24 + def parse_nums(line, negatives=True): 25 + num_re = r'-?\d+' if negatives else r'\d+' 26 + return [int(n) for n in re.findall(num_re, line)] 27 + 28 + 29 + def new_table(val, width, height): 30 + return [[val for _ in range(width)] for _ in range(height)] 31 + 32 + 33 + def transposed(matrix): 34 + """Returns the transpose of the given matrix.""" 35 + return [list(r) for r in zip(*matrix)] 36 + 37 + 38 + def rotated(matrix): 39 + """Returns the given matrix rotated 90 degrees clockwise.""" 40 + return [list(r) for r in zip(*matrix[::-1])] 41 + 42 + 43 + def mul(lst): 44 + """Like sum(), but for multiplication.""" 45 + return reduce(operator.mul, lst, 1) # NOQA 46 + 47 + 48 + def chunks(l, n): 49 + """Yield successive n-sized chunks from l.""" 50 + for i in range(0, len(l), n): 51 + yield l[i:i + n] 52 + 53 + 54 + def all_unique(lst): 55 + return len(lst) == len(set(lst)) 56 + 57 + 58 + def factors(n): 59 + """Returns the factors of n.""" 60 + return sorted( 61 + x for tup in ( 62 + [i, n // i] for i in range(1, int(n ** 0.5) + 1) 63 + if n % i == 0) 64 + for x in tup) 65 + 66 + 67 + def memoize(f): 68 + """Simple dictionary-based memoization decorator""" 69 + cache = {} 70 + 71 + def _mem_fn(*args): 72 + if args not in cache: 73 + cache[args] = f(*args) 74 + return cache[args] 75 + 76 + _mem_fn.cache = cache 77 + return _mem_fn 78 + 79 + 80 + def _eratosthenes(n): 81 + """http://stackoverflow.com/a/3941967/239076""" 82 + # Initialize list of primes 83 + _primes = [True] * n 84 + 85 + # Set 0 and 1 to non-prime 86 + _primes[0] = _primes[1] = False 87 + 88 + for i, is_prime in enumerate(_primes): 89 + if is_prime: 90 + yield i 91 + 92 + # Mark factors as non-prime 93 + for j in xrange(i * i, n, i): # NOQA 94 + _primes[j] = False 95 + 96 + 97 + def primes(n): 98 + """Return a list of primes from [2, n)""" 99 + return list(_eratosthenes(n)) 100 + 101 + 102 + def md5(msg): 103 + m = hashlib.md5() 104 + m.update(msg) 105 + return m.hexdigest() 106 + 107 + 108 + def sha256(msg): 109 + s = hashlib.sha256() 110 + s.update(msg) 111 + return s.hexdigest() 112 + 113 + 114 + def knot_hash(msg): 115 + lengths = [ord(x) for x in msg] + [17, 31, 73, 47, 23] 116 + sparse = range(0, 256) 117 + pos = 0 118 + skip = 0 119 + 120 + for _ in range(64): 121 + for l in lengths: 122 + for i in range(l // 2): 123 + x = (pos + i) % len(sparse) 124 + y = (pos + l - i - 1) % len(sparse) 125 + sparse[x], sparse[y] = sparse[y], sparse[x] 126 + 127 + pos = pos + l + skip % len(sparse) 128 + skip += 1 129 + 130 + hash_val = 0 131 + 132 + for i in range(16): 133 + res = 0 134 + for j in range(0, 16): 135 + res ^= sparse[(i * 16) + j] 136 + 137 + hash_val += res << ((16 - i - 1) * 8) 138 + 139 + return '%032x' % hash_val 140 + 141 + 142 + @total_ordering 143 + class Point: 144 + """Simple 2-dimensional point.""" 145 + def __init__(self, x, y): 146 + self.x = x 147 + self.y = y 148 + 149 + def __add__(self, other): 150 + return Point(self.x + other.x, self.y + other.y) 151 + 152 + def __sub__(self, other): 153 + return Point(self.x - other.x, self.y - other.y) 154 + 155 + def __mul__(self, n): 156 + return Point(self.x * n, self.y * n) 157 + 158 + def __div__(self, n): 159 + return Point(self.x / n, self.y / n) 160 + 161 + def __neg__(self): 162 + return Point(-self.x, -self.y) 163 + 164 + def __eq__(self, other): 165 + return self.x == other.x and self.y == other.y 166 + 167 + def __ne__(self, other): 168 + return not self == other 169 + 170 + def __lt__(self, other): 171 + return self.manhattan < other.manhattan 172 + 173 + def __str__(self): 174 + return "({}, {})".format(self.x, self.y) 175 + 176 + def __repr__(self): 177 + return "Point({}, {})".format(self.x, self.y) 178 + 179 + def __hash__(self): 180 + return hash(tuple((self.x, self.y))) 181 + 182 + def to(self, other): 183 + return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2) 184 + 185 + def to_manhattan(self, other): 186 + return abs(self.x - other.x) + abs(self.y - other.y) 187 + 188 + @property 189 + def manhattan(self): 190 + return abs(self.x) + abs(self.y) 191 + 192 + @property 193 + def distance(self): 194 + return math.sqrt(self.x ** 2 + self.y ** 2) 195 + 196 + def neighbours_4(self): 197 + return [self + p for p in DIRS_4] 198 + 199 + def neighbours_8(self): 200 + return [self + p for p in DIRS_8] 201 + 202 + 203 + DIRS_4 = DIRS = [ 204 + Point(0, 1), # north 205 + Point(1, 0), # east 206 + Point(0, -1), # south 207 + Point(-1, 0), # west 208 + ] 209 + 210 + DIRS_8 = [ 211 + Point(0, 1), # N 212 + Point(1, 1), # NE 213 + Point(1, 0), # E 214 + Point(1, -1), # SE 215 + Point(0, -1), # S 216 + Point(-1, -1), # SW 217 + Point(-1, 0), # W 218 + Point(-1, 1), # NW 219 + ]