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 template file

+46 -12
+17
2016/starter.py
··· 1 + import os # NOQA 2 + import sys # NOQA 3 + import re # NOQA 4 + import math # NOQA 5 + import fileinput 6 + from itertools import product, permutations, combinations, combinations_with_replacement # NOQA 7 + 8 + from utils import mul, factors, memoize, primes, Point # NOQA 9 + 10 + # Itertools Functions: 11 + # product('ABCD', repeat=2) AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD 12 + # permutations('ABCD', 2) AB AC AD BA BC BD CA CB CD DA DB DC 13 + # combinations('ABCD', 2) AB AC AD BC BD CD 14 + # combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC BD CC CD DD 15 + 16 + for i, line in enumerate(fileinput.input()): 17 + pass
+29 -12
2016/utils.py
··· 22 22 for x in tup) 23 23 24 24 25 - def primes(n): 26 - """Returns the sorted list of primes in the range [2, n]""" 27 - limit = n + 1 28 - not_prime = set() 29 - primes = [] 25 + def memoize(f): 26 + """Simple dictionary-based memoization decorator""" 27 + cache = {} 28 + 29 + def _mem_fn(*args): 30 + if args not in cache: 31 + cache[args] = f(*args) 32 + return cache[args] 33 + 34 + _mem_fn.cache = cache 35 + return _mem_fn 36 + 37 + 38 + def _eratosthenes(n): 39 + """http://stackoverflow.com/a/3941967/239076""" 40 + # Initialize list of primes 41 + _primes = [True] * n 42 + 43 + # Set 0 and 1 to non-prime 44 + _primes[0] = _primes[1] = False 30 45 31 - for i in range(2, limit): 32 - if i in not_prime: 33 - continue 46 + for i, is_prime in enumerate(_primes): 47 + if is_prime: 48 + yield i 34 49 35 - for f in range(i*2, limit, i): 36 - not_prime.add(f) 50 + # Mark factors as non-prime 51 + for n in xrange(i * i, n, i): 52 + _primes[n] = False 37 53 38 - primes.append(i) 39 54 40 - return primes 55 + def primes(n): 56 + """Return a list of primes from [2, n)""" 57 + return list(_eratosthenes(n)) 41 58 42 59 43 60 @total_ordering