massive overhaul. switched to pytest

master
Arne Wischer 6 years ago
parent 661d054f91
commit 5edbd2ff32
  1. 8
      .vscode/settings.json
  2. 26
      advent.py
  3. 9
      days/__init__.py
  4. 27
      days/day1.py
  5. 28
      days/day2.py
  6. 55
      days/day3.py
  7. 35
      days/day4.py
  8. 19
      days/day5.py
  9. 35
      days/day6.py
  10. 44
      days/day7.py
  11. 53
      days/day8.py
  12. 77
      days/test_comp.py
  13. 28
      days/test_day1.py
  14. 29
      days/test_day2.py
  15. 56
      days/test_day3.py
  16. 35
      days/test_day4.py
  17. 20
      days/test_day5.py
  18. 35
      days/test_day6.py
  19. 45
      days/test_day7.py
  20. 54
      days/test_day8.py
  21. 2
      pytest.ini

@ -2,5 +2,11 @@
"python.linting.pylintEnabled": false, "python.linting.pylintEnabled": false,
"python.linting.pycodestyleEnabled": true, "python.linting.pycodestyleEnabled": true,
"python.linting.enabled": true, "python.linting.enabled": true,
"autoDocstring.docstringFormat": "google" "autoDocstring.docstringFormat": "google",
"python.testing.pytestArgs": [
"days"
],
"python.testing.unittestEnabled": false,
"python.testing.nosetestsEnabled": false,
"python.testing.pytestEnabled": true
} }

@ -1,28 +1,6 @@
from days import * from days import *
import unittest import pytest
def suite():
suite = unittest.TestSuite()
suite.addTest(Day1('test_day1a'))
suite.addTest(Day1('test_day1b'))
suite.addTest(Day2('test_day2a'))
suite.addTest(Day2('test_day2b'))
suite.addTest(Day3('test_day3a'))
suite.addTest(Day3('test_day3b'))
suite.addTest(Day4('test_day4a'))
suite.addTest(Day4('test_day4b'))
suite.addTest(Day5('test_day5a'))
suite.addTest(Day5('test_day5b'))
suite.addTest(Day6('test_day6a'))
suite.addTest(Day6('test_day6b'))
suite.addTest(Day7('test_day7a'))
suite.addTest(Day7('test_day7b'))
suite.addTest(Day8('test_day8a'))
suite.addTest(Day8('test_day8b'))
return suite
if __name__ == "__main__": if __name__ == "__main__":
runner = unittest.TextTestRunner(verbosity=2) pytest.main()
runner.run(suite())

@ -1,8 +1 @@
from .day1 import Day1 from .comp import *
from .day2 import Day2
from .day3 import Day3
from .day4 import Day4
from .day5 import Day5
from .day6 import Day6
from .day7 import Day7
from .day8 import Day8

@ -1,27 +0,0 @@
import unittest
import os
class Day1(unittest.TestCase):
inputfile = os.path.join(os.path.dirname(__file__), "input/day1_input")
def calc_fuel(self, mass):
fuel = mass // 3 - 2
return fuel + self.calc_fuel(fuel) if fuel > 0 else 0
def test_day1a(self):
fuel = 0
with open(self.inputfile) as fp:
for _, line in enumerate(fp):
fuel += int(line) // 3 - 2
self.assertEqual(fuel, 3402609)
def test_day1b(self):
sumfuel = 0
with open(self.inputfile) as fp:
for _, line in enumerate(fp):
sumfuel = 0
while line:
sumfuel += self.calc_fuel(int(line))
line = fp.readline()
self.assertEqual(sumfuel, 5101025)

@ -1,28 +0,0 @@
import unittest
import os
from typing import List
from .comp import OpcodeComputer
class Day2(unittest.TestCase):
inputfile = os.path.join(os.path.dirname(__file__), "input/day2_input")
def test_day2a(self):
comp = OpcodeComputer(self.inputfile)
comp.memory[1] = 12
comp.memory[2] = 2
self.assertEqual(comp.process_all(), 5098658)
def test_day2b(self):
comp = OpcodeComputer(self.inputfile)
a: int = 0
b: int = 0
for a, b in [(x, y) for x in range(100) for y in range(100)]:
comp.reset()
comp.memory[1] = int(a)
comp.memory[2] = int(b)
result = comp.process_all()
if result == 19690720:
break
self.assertEqual(100 * a + b, 5064)

@ -1,55 +0,0 @@
import unittest
import os
import sys
class Day3(unittest.TestCase):
inputfile = os.path.join(os.path.dirname(__file__), "input/day3_input")
def draw_path(self, inst):
path = set()
dists = {}
cnt = 0
ptr = (0, 0)
for d, l in ((x[0], x[1:]) for x in inst.split(',')):
for _ in range(int(l)):
if d == 'D':
ptr = (ptr[0], ptr[1] - 1)
elif d == 'R':
ptr = (ptr[0] + 1, ptr[1])
elif d == 'U':
ptr = (ptr[0], ptr[1] + 1)
else:
ptr = (ptr[0] - 1, ptr[1])
cnt += 1
if ptr not in dists or dists[ptr] > cnt:
dists[ptr] = cnt
path.add(ptr)
return (path, dists)
def test_day3a(self):
paths = []
result = sys.maxsize
with open(self.inputfile) as fp:
for line in fp.readlines():
paths.append(self.draw_path(line)[0])
for x, y in paths[0].intersection(paths[1]):
dist = abs(x) + abs(y)
result = dist if dist < result else result
self.assertEqual(result, 399)
def test_day3b(self):
paths = []
distances = []
result = sys.maxsize
with open(self.inputfile) as fp:
for line in fp.readlines():
computed = self.draw_path(line)
paths.append(computed[0])
distances.append(computed[1])
for point in paths[0].intersection(paths[1]):
dist = distances[0][point] + distances[1][point]
result = dist if dist < result else result
self.assertEqual(result, 15678)

@ -1,35 +0,0 @@
import unittest
import os
from collections import Counter
class Day4(unittest.TestCase):
def check_num(self, num):
numarr = [int(d) for d in (str(num))]
for p in range(1, 6):
if numarr[p-1] > numarr[p]:
return False
c = Counter(str(num))
return len({k: v for k, v in c.items() if v >= 2}) > 0
def check_num_grp(self, num):
numarr = [int(d) for d in (str(num))]
for p in range(1, 6):
if numarr[p-1] > numarr[p]:
return False
c = Counter(str(num))
return len({k: v for k, v in c.items() if v == 2}) > 0
def test_day4a(self):
counter = 0
for num in range(168630, 718099):
if self.check_num(num) is True:
counter += 1
self.assertEqual(counter, 1686)
def test_day4b(self):
counter = 0
for num in range(168630, 718099):
if self.check_num_grp(num) is True:
counter += 1
self.assertEqual(counter, 1145)

@ -1,19 +0,0 @@
import unittest
import os
from .comp import OpcodeComputer
class Day5(unittest.TestCase):
inputfile = os.path.join(os.path.dirname(__file__), "input/day5_input")
def test_day5a(self):
sut = OpcodeComputer(self.inputfile)
outp = list(sut.process_op([1]))
self.assertEqual(int(outp[-1]), 8332629)
def test_day5b(self):
sut = OpcodeComputer(self.inputfile)
outp = list(sut.process_op([5]))
self.assertEqual(int(outp[0]), 8805067)

@ -1,35 +0,0 @@
import unittest
import os
from typing import Dict
class Day6(unittest.TestCase):
def get_code(self) -> Dict[str, str]:
inputfile = os.path.join(os.path.dirname(__file__), "input/day6_input")
with open(inputfile) as fp:
return {x[1].rstrip(): x[0] for x in
(y.split(')') for y in fp.readlines())}
def test_day6a(self):
orbs = self.get_code()
cnt = 0
for orb in orbs.keys():
n = orb
cnt -= 1
while n:
n = orbs.get(n)
cnt += 1
self.assertEqual(cnt, 241064)
def test_day6b(self):
orbs = self.get_code()
c = orbs['YOU']
k = []
while c:
k.append(c)
c = orbs.get(c)
c = orbs['SAN']
while c:
k.remove(c) if c in k else k.append(c)
c = orbs.get(c)
self.assertEqual(len(k), 418)

@ -1,44 +0,0 @@
import unittest
import os
from .comp import OpcodeComputer
import itertools
class Day7(unittest.TestCase):
inputfile = os.path.join(os.path.dirname(__file__), "input/day7_input")
def test_day7a(self):
com = OpcodeComputer(self.inputfile)
configs = itertools.permutations(range(5), 5)
res: int = 0
for conf in configs:
sig: int = 0
for phase in conf:
sig = int(list(com.process_op([phase, sig]))[0])
res = sig if sig > res else res
self.assertEqual(res, 21000)
def test_day7b(self):
"""
Shoutout to OverjoyedBanana for his helpful solution
https://www.reddit.com/r/adventofcode/comments/e7om28/2019_day_7_part_2_python3_help_with/fa3bh4w/
https://pastebin.com/cyLTHUYV
"""
com = OpcodeComputer(self.inputfile)
res: int = 0
for config in itertools.permutations(range(5, 10), 5):
sig: int = 0
buffer = [[conf] for conf in config]
comps = list(map(com.process_op, buffer))
try:
while True:
for i in range(5):
buffer[i].append(sig)
sig = int(next(comps[i]))
except StopIteration:
pass
res = sig if sig > res else res
self.assertEqual(res, 61379886)

@ -1,53 +0,0 @@
import unittest
import os
import sys
class Day8(unittest.TestCase):
imgsize = 25 * 6
def get_image(self):
inputfile = os.path.join(os.path.dirname(__file__), "input/day8_input")
with open(inputfile) as fp:
img = [int(k) for k in str(fp.readline())]
breaks = [self.imgsize*k for k in range(len(img)//self.imgsize+1)]
return [img[b:e] for b, e in zip(breaks, breaks[1:])]
def test_day8a(self):
layers = self.get_image()
min = sys.maxsize
layer = 0
for i, l in enumerate(layers):
z = l.count(0)
if z < min:
min = z
layer = i
solution = layers[layer].count(1)*layers[layer].count(2)
self.assertEqual(solution, 2806)
def test_day8b(self):
layers = self.get_image()
result = [2 for i in range(self.imgsize)]
for pos in range(self.imgsize):
for l in layers:
result[pos] = l[pos] if result[pos] == 2 else result[pos]
result = ['#' if x == 0 else '.' if x == 1 else ' ' for x in result]
for k in range(len(result)):
# print(result[k], end='')
if (k+1) % 25 == 0:
# print('')
pass
expected = """\
....#...####..##..##...##\
###.#.##.####.#.##.#.##.#\
##.##...#####.#.##.#...##\
#.###.##.####.#....#.##.#\
.####.##.#.##.#.##.#.##.#\
....#...###..##.##.#...##\
"""
self.assertEqual("".join(result), expected)

@ -1,31 +1,66 @@
import unittest import unittest
import os import os
from .comp import OpcodeComputer from . import OpcodeComputer
class Test_OpcodeComputer(unittest.TestCase): inputfile = os.path.join(os.path.dirname(__file__), "input/day9_input")
inputfile = os.path.join(os.path.dirname(__file__), "input/day9_input")
def test_addition(self):
com = OpcodeComputer(mem="1,0,0,0,99")
com.process_all()
self.assertEqual(com.memory, [2, 0, 0, 0, 99])
def test_multiplication(self): def test_addition():
com = OpcodeComputer(mem="2,3,0,3,99") com = OpcodeComputer(mem="1,0,0,0,99")
com.process_all() com.process_all()
self.assertEqual(com.memory, [2, 3, 0, 6, 99]) assert com.memory == [2, 0, 0, 0, 99]
def test_multiplication2(self):
com = OpcodeComputer(mem="2,4,4,5,99,0")
com.process_all()
self.assertEqual(com.memory, [2, 4, 4, 5, 99, 9801])
def test_addition2(self): def test_multiplication():
com = OpcodeComputer(mem="1,1,1,4,99,5,6,0,99") com = OpcodeComputer(mem="2,3,0,3,99")
com.process_all() com.process_all()
self.assertEqual(com.memory, [30, 1, 1, 4, 2, 5, 6, 0, 99]) assert com.memory == [2, 3, 0, 6, 99]
if __name__ == "__main__": def test_multiplication2():
unittest.main() com = OpcodeComputer(mem="2,4,4,5,99,0")
com.process_all()
assert com.memory == [2, 4, 4, 5, 99, 9801]
def test_addition2():
com = OpcodeComputer(mem="1,1,1,4,99,5,6,0,99")
com.process_all()
assert com.memory == [30, 1, 1, 4, 2, 5, 6, 0, 99]
def test_position1():
com = OpcodeComputer(mem="3,9,8,9,10,9,4,9,99,-1,8")
res = list(com.process_op([8]))
assert res[0] == '1'
def test_position2():
com = OpcodeComputer(mem="3,9,7,9,10,9,4,9,99,-1,8")
res = list(com.process_op([7]))
assert res[0] == '1'
def test_immediate1():
com = OpcodeComputer(mem="3,3,1108,-1,8,3,4,3,99")
res = list(com.process_op([8]))
assert res[0] == '1'
def test_immediate2():
com = OpcodeComputer(mem="3,3,1107,-1,8,3,4,3,99")
res = list(com.process_op([7]))
assert res[0] == '1'
def test_jump_position():
com = OpcodeComputer(mem="3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9")
res = list(com.process_op([0]))
assert res[0] == '0'
def test_jump_immediate():
com = OpcodeComputer(mem="3,3,1105,-1,9,1101,0,0,12,4,12,99,1")
res = list(com.process_op([0]))
assert res[0] == '0'

@ -0,0 +1,28 @@
import os
inputfile = os.path.join(os.path.dirname(__file__), "input/day1_input")
def calc_fuel(mass):
fuel = mass // 3 - 2
return fuel + calc_fuel(fuel) if fuel > 0 else 0
def test_day1a():
fuel = 0
with open(inputfile) as fp:
for _, line in enumerate(fp):
fuel += int(line) // 3 - 2
assert fuel == 3402609
def test_day1b():
sumfuel = 0
with open(inputfile) as fp:
for _, line in enumerate(fp):
sumfuel = 0
while line:
sumfuel += calc_fuel(int(line))
line = fp.readline()
assert sumfuel == 5101025

@ -0,0 +1,29 @@
import os
from . import OpcodeComputer
inputfile = os.path.join(os.path.dirname(__file__), "input/day2_input")
def test_day2a():
comp = OpcodeComputer(inputfile)
comp.memory[1] = 12
comp.memory[2] = 2
assert comp.process_all() == 5098658
def test_day2b():
comp = OpcodeComputer(inputfile)
a: int = 0
b: int = 0
for a, b in [(x, y) for x in range(100) for y in range(100)]:
comp.reset()
comp.memory[1] = int(a)
comp.memory[2] = int(b)
result = comp.process_all()
if result == 19690720:
break
assert 100 * a + b == 5064

@ -0,0 +1,56 @@
import os
import sys
inputfile = os.path.join(os.path.dirname(__file__), "input/day3_input")
def draw_path(inst):
path = set()
dists = {}
cnt = 0
ptr = (0, 0)
for d, l in ((x[0], x[1:]) for x in inst.split(',')):
for _ in range(int(l)):
if d == 'D':
ptr = (ptr[0], ptr[1] - 1)
elif d == 'R':
ptr = (ptr[0] + 1, ptr[1])
elif d == 'U':
ptr = (ptr[0], ptr[1] + 1)
else:
ptr = (ptr[0] - 1, ptr[1])
cnt += 1
if ptr not in dists or dists[ptr] > cnt:
dists[ptr] = cnt
path.add(ptr)
return (path, dists)
def test_day3a():
paths = []
result = sys.maxsize
with open(inputfile) as fp:
for line in fp.readlines():
paths.append(draw_path(line)[0])
for x, y in paths[0].intersection(paths[1]):
dist = abs(x) + abs(y)
result = dist if dist < result else result
assert result == 399
def test_day3b():
paths = []
distances = []
result = sys.maxsize
with open(inputfile) as fp:
for line in fp.readlines():
computed = draw_path(line)
paths.append(computed[0])
distances.append(computed[1])
for point in paths[0].intersection(paths[1]):
dist = distances[0][point] + distances[1][point]
result = dist if dist < result else result
assert result == 15678

@ -0,0 +1,35 @@
from collections import Counter
def check_num(num):
numarr = [int(d) for d in (str(num))]
for p in range(1, 6):
if numarr[p-1] > numarr[p]:
return False
c = Counter(str(num))
return len({k: v for k, v in c.items() if v >= 2}) > 0
def check_num_grp(num):
numarr = [int(d) for d in (str(num))]
for p in range(1, 6):
if numarr[p-1] > numarr[p]:
return False
c = Counter(str(num))
return len({k: v for k, v in c.items() if v == 2}) > 0
def test_day4a():
counter = 0
for num in range(168630, 718099):
if check_num(num) is True:
counter += 1
assert counter == 1686
def test_day4b():
counter = 0
for num in range(168630, 718099):
if check_num_grp(num) is True:
counter += 1
assert counter == 1145

@ -0,0 +1,20 @@
import os
from . import OpcodeComputer
inputfile = os.path.join(os.path.dirname(__file__), "input/day5_input")
def test_day5a():
sut = OpcodeComputer(inputfile)
outp = list(sut.process_op([1]))
assert int(outp[-1]) == 8332629
def test_day5b():
sut = OpcodeComputer(inputfile)
outp = list(sut.process_op([5]))
assert int(outp[0]) == 8805067

@ -0,0 +1,35 @@
import os
from typing import Dict
def get_code() -> Dict[str, str]:
inputfile = os.path.join(os.path.dirname(__file__), "input/day6_input")
with open(inputfile) as fp:
return {x[1].rstrip(): x[0] for x in
(y.split(')') for y in fp.readlines())}
def test_day6a():
orbs = get_code()
cnt = 0
for orb in orbs.keys():
n = orb
cnt -= 1
while n:
n = orbs.get(n)
cnt += 1
assert cnt == 241064
def test_day6b():
orbs = get_code()
c = orbs['YOU']
k = []
while c:
k.append(c)
c = orbs.get(c)
c = orbs['SAN']
while c:
k.remove(c) if c in k else k.append(c)
c = orbs.get(c)
assert len(k) == 418

@ -0,0 +1,45 @@
import itertools
import os
from . import OpcodeComputer
inputfile = os.path.join(os.path.dirname(__file__), "input/day7_input")
def test_day7a():
com = OpcodeComputer(inputfile)
configs = itertools.permutations(range(5), 5)
res: int = 0
for conf in configs:
sig: int = 0
for phase in conf:
sig = int(list(com.process_op([phase, sig]))[0])
res = sig if sig > res else res
assert res == 21000
def test_day7b():
"""
Shoutout to OverjoyedBanana for his helpful solution
https://www.reddit.com/r/adventofcode/comments/e7om28/2019_day_7_part_2_python3_help_with/fa3bh4w/
https://pastebin.com/cyLTHUYV
"""
com = OpcodeComputer(inputfile)
res: int = 0
for config in itertools.permutations(range(5, 10), 5):
sig: int = 0
buffer = [[conf] for conf in config]
comps = list(map(com.process_op, buffer))
try:
while True:
for i in range(5):
buffer[i].append(sig)
sig = int(next(comps[i]))
except StopIteration:
pass
res = sig if sig > res else res
assert res == 61379886

@ -0,0 +1,54 @@
import os
import sys
imgsize = 25 * 6
def get_image():
inputfile = os.path.join(os.path.dirname(__file__), "input/day8_input")
with open(inputfile) as fp:
img = [int(k) for k in str(fp.readline())]
breaks = [imgsize*k for k in range(len(img)//imgsize+1)]
return [img[b:e] for b, e in zip(breaks, breaks[1:])]
def test_day8a():
layers = get_image()
min = sys.maxsize
layer = 0
for i, l in enumerate(layers):
z = l.count(0)
if z < min:
min = z
layer = i
solution = layers[layer].count(1)*layers[layer].count(2)
assert solution == 2806
def test_day8b():
layers = get_image()
result = [2 for i in range(imgsize)]
for pos in range(imgsize):
for l in layers:
result[pos] = l[pos] if result[pos] == 2 else result[pos]
result = ['#' if x == 0 else '.' if x == 1 else ' ' for x in result]
for k in range(len(result)):
# print(result[k], end='')
if (k+1) % 25 == 0:
# print('')
pass
expected = """\
....#...####..##..##...##\
###.#.##.####.#.##.#.##.#\
##.##...#####.#.##.#...##\
#.###.##.####.#....#.##.#\
.####.##.#.##.#.##.#.##.#\
....#...###..##.##.#...##\
"""
assert "".join(result) == expected

@ -0,0 +1,2 @@
[pytest]
junit_family=legacy
Loading…
Cancel
Save