题目内容:根据每日气温列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高, 请在该位置用 0 来代替。输入格式:一行以Python表达式格式给出的列表,包含数个整数。输出格式:整数组成的列表,直接使用print输出。输入样例:[73, 74, 75, 71, 69, 72, 76, 73]。输出样例:[1, 1, 4, 2, 1, 1, 0, 0]。
思路是单调递减栈,温度大于栈顶元素,栈顶元素出栈,温度入栈;后面没有温度输出0.
初学者不知道哪里有问题,希望得到帮助!
from pythonds.basic.stack import Stack
def daily_temperatures(temperature):
s = Stack()
wait_days = [1]
s.push(0)
for i in range(len(temperature)):
while not s.isEmpty() and temperature[i] >= temperature[s.peek()]:
wait_days.append(i - s.peek())
s.pop()
if s.isEmpty():
wait_days.append(0)
s.push(i)
return wait_days
temperature_list = eval(input())
print(daily_temperatures(temperature_list))