#!/usr/bin/env python3 import numpy as np import scipy.ndimage.filters as filters import scipy.ndimage.morphology as morphology arr = np.array([[int(n) for n in line.strip()] for line in open("input.txt")]) # https://stackoverflow.com/questions/3986345/how-to-find-the-local-minima-of-a-smooth-multidimensional-array-in-numpy-efficie neighborhood = morphology.generate_binary_structure(len(arr.shape), 1) local_min = (filters.minimum_filter(arr, footprint=neighborhood) == arr) local_max = (filters.maximum_filter(arr, footprint=neighborhood) == arr) local_min_without_plateau = np.logical_and(local_min, np.logical_not(local_max)) local_min_locations = np.where(local_min_without_plateau) local_min_values = arr[local_min_locations] print(sum(local_min_values)+len(local_min_values))