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.

Update 2015/day20.py

Cache previous calls to factors() function.

+19 -12
+19 -12
2015/day20.py
··· 1 1 import fileinput 2 2 3 3 PRESENTS = int(fileinput.input()[0].strip()) 4 + CACHE = {} 5 + 4 6 5 7 def factors(n): 6 - return set(x for tup in ([i, n//i] 7 - for i in range(1, int(n**0.5)+1) if n % i == 0) for x in tup) 8 + if n in CACHE: 9 + return CACHE[n] 10 + 11 + CACHE[n] = set() 12 + 13 + for i in range(1, int(n**0.5) + 1): 14 + if n % i == 0: 15 + CACHE[n] |= set([i, n//i]) 16 + 17 + return CACHE[n] 18 + 8 19 9 20 house = 1 10 - 11 - while True: 12 - if sum(factors(house)) * 10 >= PRESENTS: 13 - print "Lowest house number #1:", house 14 - break 21 + while sum(factors(house)) * 10 < PRESENTS: 15 22 house += 1 16 23 24 + print "Lowest house number #1:", house 25 + 17 26 house = 1 27 + while sum(x for x in factors(house) if (x * 50 >= house)) * 11 < PRESENTS: 28 + house += 1 18 29 19 - while True: 20 - if sum(x for x in factors(house) if (x * 50 >= house)) * 11 >= PRESENTS: 21 - print "Lowest house number #2:", house 22 - break 23 - house += 1 30 + print "Lowest house number #2:", house