- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# Program to find how many total amount of rain we can catch in Python

Suppose we have an array of n non-negative integers. These are representing a height where the width of each bar is 1, we have to compute how much water it is able to catch after raining. So the map will be like −

Here we can see there are 8 blue boxes, so the output will be 8.

To solve this, we will follow these steps −

- Define a stack st, water := 0 and i := 0
- while i < size of height
- if is stack is empty or height[stack top] >= height[i], then push i into stack, increase i by 1
- otherwise
- x := stack top element, delete top from stack
- if stack is not empty, then
- temp := min of height[stack top element] and height[i]
- dest := i – stack top element – 1
- water := water + dist * (temp – height[x])

- return water

Let us see the following implementation to get better understanding −

## Example

class Solution(object): def trap(self, height): stack = [] water = 0 i=0 while i<len(height): if len(stack) == 0 or height[stack[-1]]>=height[i]: stack.append(i) i+=1 else: x = stack[-1] stack.pop() if len(stack) != 0: temp = min(height[stack[-1]],height[i]) dist = i - stack[-1]-1 water += dist*(temp - height[x]) return water ob = Solution() print(ob.trap([2,5,2,0,5,8,8]))

## Input

[2,5,2,0,5,8,8]

## Output

8

- Related Articles
- Program to find total amount of money we have in bank in Python
- Program to find how many ways we can climb stairs in Python
- Program to find maximum how many water bottles we can drink in Python
- Program to find maximum amount of coin we can collect from a given matrix in Python
- Program to find how many years it will take to reach t amount in Python
- Program to count how many times we can find "pizza" with given string characters in Python
- C++ code to find out the total amount of sales we made
- Program to Find Out the Amount of Rain to be Caught between the Valleys in C++
- Program to find maximum amount we can get by taking different items within the capacity in Python
- Program to check how many ways we can choose empty cells of a matrix in python
- Program to find how many ways we can climb stairs (maximum steps at most k times) in Python
- Program to find the formatted amount of cents of given amount in Python
- Program to find out how many transfer requests can be satisfied in Python
- Program to count how many ways we can divide the tree into two trees in Python
- Program to count how many ways we can cut the matrix into k pieces in python

Advertisements