- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Daily Temperatures in Python
Suppose we have a list of daily temperatures T, we have to return a list such that, for each day in the input, shows how many days we would have to wait until a warmer temperature. If there is no future day for which this is possible, store 0 instead. For example, if T = [73, 74, 75, 71, 69, 72, 76, 73], output will be [1, 1, 4, 2, 1, 1, 0, 0].
To solve this, we will follow these steps −
- ans := an array of size same as T, and fill this with 0
- define one stack, and insert 0 into the stack, and i := 1
- while i < length of T
- while stack element count is not 0 and T[i] > T[stack top element]
- index := stack top element
- ans[index] := i – index
- delete top element from stack
- if length of stack is 0 or T[i] <= T[stack top element]
- insert i into stack
- increase i by 1
- while stack element count is not 0 and T[i] > T[stack top element]
- return ans
Example(Python)
Let us see the following implementation to get a better understanding −
class Solution(object): def dailyTemperatures(self, T): ans = [0 for i in range(len(T))] stack = [] stack.append(0) i=1 while i <len(T): while len(stack) and T[i]>T[stack[-1]]: index = stack[-1] ans[index] = i-index stack.pop() if not len(stack) or T[i]<=T[stack[-1]]: stack.append(i) i+=1 return ans ob1 = Solution() print(ob1.dailyTemperatures([73,74,75,71,69,72,76,73]))
Input
[73,74,75,71,69,72,76,73]
Output
[1, 1, 4, 2, 1, 1, 0, 0]
- Related Articles
- Daily Temperatures in C++
- The daily maximum temperatures (in degree Celsius) recorded in a certain city during the month of November are as follows:
- Python Pandas - Round the Timedelta with daily frequency
- Python Pandas - Return a new Timedelta with daily ceiling resolution
- Python Pandas - Return a new Timedelta with daily floored resolution
- Python Pandas - Return the Period object as a timestamp with daily frequency
- Why do different substances catch fire at different temperatures?
- How do mobiles help us in daily life?
- How to stay healthy in your daily life?
- What are the causes of an increase or a decrease in temperatures?
- Give three examples exhibiting inertia in our daily life.
- Evolution of Cord Cutting: Digital Shifts in Daily Life
- Python Pandas - Change the frequency of the given Period object from Seconds to Daily frequency
- Give me 5 daily routine makeup tips
- Why are TV serials called daily soaps?

Advertisements