- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find out the buildings that have a better view in Python
Suppose, we are provided with an array that contains the heights of different buildings. The buildings are located on a line, and a building has a better view if it is not obstructed by another taller building. So provided the array containing heights, we have to find out the buildings that do not have other taller buildings to obstruct the view from them. The indices are returned from the array that satisfies the criteria.
So, if the input is like height = [5, 6, 8, 7], then the output will be [2, 3]. The buildings in array index 0 and 1 is obstructed by the building at index 2. The building at index 2 and 3 are not blocked because the taller building at position 2 is situated behind the shorter building at position 3.
To solve this, we will follow these steps −
- res := a new list
- h := 0
- for i in range (size of heights - 1) to -1, decrease by 1, do
- if heights[i] > h , then
- insert i at the end of res
- h := heights[i]
- if heights[i] > h , then
- return the reverse of list res
Example
Let us see the following implementation to get better understanding −
def solve(heights): res, h = [], 0 for i in range(len(heights) - 1, -1, -1): if heights[i] > h: res.append(i) h = heights[i] return res[::-1] print(solve([5, 6, 8, 7]))
Input
[5, 6, 8, 7]
Output
[2, 3]