Stuck On Rain Water

Link to project:
https://www.codecademy.com/courses/technical-interview-practice-python/projects/rain-water
.
Look:
Task question:
21.

Within optimize_rain_water() at the top of the function make a total variable set to 0 .

Make one final loop through histogram :

  1. Take the min() of the two maxes at the current index (one from left_maxes , one from right_maxes )
  2. Subtract the current value from the result of min()
  3. Add the result to total

Test out your optimized function with the inputs.

Code:

from time import time ####### TEST INPUTS HERE small = [1, 0, 1] medium = [4, 2, 1, 3, 0, 1, 2] edge_case = [0, 2, 0] ####### NAIVE SOLUTION HERE def rain_water(histogram: list): total_water = 0 for idx in range(1, len(histogram) - 1): left_values = histogram[:idx] left_max = max(left_values) print(f"Left max is: {left_max}") right_values = histogram[idx + 1:] right_max = max(right_values) print(f"Right max is: {right_max}") fill_mark = min(left_max, right_max) - idx fill_mark += total_water if fill_mark > -1: total_water += fill_mark - idx return total_water start = time() rain_water(small) rain_water(medium) rain_water(edge_case) rain_water([0, 1, 0]) print(time() - start) ####### OPTIMIZED SOLUTION HERE def optimized_rain_water(histogram): total = 0 max_value = histogram[0] left_maxes = [] right_maxes = [] for idx in range(len(histogram)): print(f"Left max is {histogram[idx]}") if histogram[idx] > max_value: left_maxes.append(histogram[idx]) max_value = histogram[-1] for idx in range(len(histogram) - 1, -1): print(f"Right max is {histogram[idx]}") if histogram[idx] > max_value: right_maxes.append(histogram[idx]) max_value = histogram[0] right_maxes.reverse() for idx in range(len(histogram)): total = min(left_maxes[idx], right_maxes[idx]) - idx start = time() optimized_rain_water(small) optimized_rain_water(medium) optimized_rain_water(edge_case) ####### BENCHMARKING HERE print(time() - start) start = time() rain_water(small) rain_water(medium) rain_water(edge_case) print(start - time()) start = time() optimized_rain_water([i for i in range(10000)]) print(time() - start) start = time() rain_water([i for i in range(10000)]) print(time() - start)

I am unable to get rid off the index error.

I think line19, should subtracting the value of the position “fill_mark = min(left_max, right_max) - historgram[idx]” instead of subtracting the index.

Then line 20, it should be " total_water += fill_mark" because you need to add fill_mark into total_water not the opposite way.