Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Stack of flooded areas solution in Clear category for Flood Area by Rcp8jzd
from typing import List
from collections import namedtuple
Flood = namedtuple('Flood', ['start', 'area'])
def flood_area(diagram: str) -> List[int]:
descending = [] # list storing the indexes of descending slopes
floods = [] # list storing the start and area of every flood
for index, slope in enumerate(diagram):
if slope == "\\":
descending.append(index)
elif slope == "/" and descending:
start = descending.pop()
area = index - start
# Merge floods if necessary
while floods and floods[-1].start > start:
area += floods[-1].area
del floods[-1]
floods.append(Flood(start=start, area=area))
return [flood.area for flood in floods]
if __name__ == '__main__':
print("Example:")
print(list(flood_area(r'\\//')))
assert list(flood_area(r'\\//')) == [4], 'valley'
assert list(flood_area(r'/\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/')) == [4, 2, 1, 19, 9], 'mountains'
assert list(flood_area(r'_/_\_')) == [], 'hill'
print("Coding complete? Click 'Check' to earn cool rewards!")
April 26, 2020
Comments: