Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
9-liner: generator with itertools.accumulate for altitudes solution in Clear category for Flood Area by Phil15
import itertools as it, contextlib
DZ = dict(zip(r'\_/', (-1, 0, 1))) # elevation changes.
def flood_area(diagram):
# diagram = diagram.lstrip('_/').rstrip(r'\_') # cut useless parts
# Determine relative altitude in every point of the diagram.
j, altitudes = 0, [0] + list(it.accumulate(map(DZ.get, diagram)))
# diagram[i:j] will be a flood zone.
for i, (altitude, symbol) in enumerate(zip(altitudes, diagram)):
# A flood zone always starts with '\'.
# j is the end of the previous zone
# i the start (?) of the next zone, so i >= j.
if i >= j and symbol == '\\':
with contextlib.suppress(ValueError):
j = altitudes.index(altitude, i + 1)
yield sum(altitude - altitudes[k] for k in range(i + 1, j))
Feb. 21, 2019
Comments: