22
loading...
This website collects cookies to deliver better user experience
import numpy as np
lines = np.loadtxt("day_1.txt")
lines[1:] > lines[:-1]
means "do the greater-than comparison for each element on a list that is a shifted version of the data and itself (minus the last element, to match up the lengths)". The result is an array of True or False depending on whether that position had an increase or not. We can sum those (effectively counting the True values) to find the result:increases = (lines[1:] > lines[:-1]).sum()
[1, 1, 1]
. The "valid"
argument ensures there's no extra padding either side the result, so it's the same size as the input data.convolved = np.convolve(lines, [1, 1, 1], "valid")
increases = (convolved[1:] > convolved[:-1]).sum()
a[i+1] + a[i+2] + a[i+3] > a[i] + a[i+1] + a[i+2]
a[i+3] > [ai]
. Therefore Part 2 can be achieved using the same element-wise calculation as Part 1, by shifting the lists by 3 rather than 1, skipping needing to do any convolution:increases = (lines[3:] > lines[:-3]).sum()
import numpy as np
lines = np.loadtxt("day_1.txt")
increases = (lines[1:] > lines[:-1]).sum()
print("Part 1 result:", increases)
increases = (lines[3:] > lines[:-3]).sum()
print("Part 2 result:", increases)