Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Flood Area by freeman_lex
from collections.abc import Iterable
def flood_area(diagram: str) -> Iterable[int]:
diagram = diagram.lstrip("_/").rstrip("\\_")
heights = [0]
for c in diagram:
heights.append(heights[-1] + (c == "/") - (c == "\\"))
while heights:
start = heights.pop(0)
if start in heights:
end = heights.index(start)
hole = [start] + heights[:end + 1]
if len(set(hole)) > 1 and start == max(hole):
hole = [hole[0] - i for i in hole]
area = sum((a + b) / 2 for a, b in zip(hole, hole[1:]))
yield int(area)
heights = heights[end:]
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!")
May 1, 2023