如何在python中实现堆栈?
这个问题可能使用python中的堆栈概念。 我的代码如下,但它总是得到时间限制超过(TLE)错误。 我想问题是我设计的算法太慢了,因为有两个循环。 我想知道如何实现堆栈的概念,并且在这个问题中只使用一个循环。请指导我并帮助我修改代码,非常感谢 输入:包括一行,其中包含多个整数,表示每次的分数,数字之间用空格分隔如何在python中实现堆栈?,python,data-structures,stack,Python,Data Structures,Stack,这个问题可能使用python中的堆栈概念。 我的代码如下,但它总是得到时间限制超过(TLE)错误。 我想问题是我设计的算法太慢了,因为有两个循环。 我想知道如何实现堆栈的概念,并且在这个问题中只使用一个循环。请指导我并帮助我修改代码,非常感谢 输入:包括一行,其中包含多个整数,表示每次的分数,数字之间用空格分隔 inp = [int(i) for i in input().split()] #create a function to calculate intervals def cal_in
inp = [int(i) for i in input().split()]
#create a function to calculate intervals
def cal_interval(lst):
lenth = len(inp)
output_lst = []
for i in range(lenth):
#set counter
count = 1
#set iteraion number
iter_num = 0
for j in range(i+1, lenth):
iter_num += 1
if inp[j] > inp[i]:
output_lst.append(count)
break
else:
count += 1
if iter_num == (lenth-i-1):
output_lst.append(0)
break
#last number
output_lst.append(0)
#from int list transformed into str list
output_lst = [str(i) for i in output_lst]
#join by spaces
space = ' '
interval_str = space.join(output_lst)
return interval_str
print (cal_interval(inp))
输出:包括一行,其中包含多个整数,表示每个分数增加时的间隔频率(如果分数没有增加,则返回0),数字之间用空格分隔
inp = [int(i) for i in input().split()]
#create a function to calculate intervals
def cal_interval(lst):
lenth = len(inp)
output_lst = []
for i in range(lenth):
#set counter
count = 1
#set iteraion number
iter_num = 0
for j in range(i+1, lenth):
iter_num += 1
if inp[j] > inp[i]:
output_lst.append(count)
break
else:
count += 1
if iter_num == (lenth-i-1):
output_lst.append(0)
break
#last number
output_lst.append(0)
#from int list transformed into str list
output_lst = [str(i) for i in output_lst]
#join by spaces
space = ' '
interval_str = space.join(output_lst)
return interval_str
print (cal_interval(inp))
有两组测试数据如下:
Sample Input 1: 89 56 78 9 81 7
Sample Output 1: 0 1 2 1 0 0
Sample Input 2: 76 3 60 57 11 72 73 86 27 91 56 58 21 2
Sample Output 2: 7 1 3 2 1 1 1 2 1 0 1 0 0 0
实际上,您可以使用带有一些理解的切片来执行此操作,而且
next
将非常有用,因为您可以为其提供一个默认值:
def get_intervals(data):
for score, *nums in (data[i:] for i in range(len(data))):
yield next((i for i, n in enumerate(nums, 1) if n > score), 0)
我在这里所做的就是每次迭代,score
是数据中的下一个数字,nums
是它之后的其余数字。然后使用next,如果第一个值高于分数,它将获取nums中第一个值的索引,否则默认为0
因此,您只需打印get\u interval
的结果即可代替cal\u interval
:
print(' '.join(get_intervals([89, 56, 78, 9, 81, 7])))
print(' '.join(get_intervals( [76, 3, 60, 57, 11, 72, 73, 86, 27, 91, 56, 58, 21, 2])))
结果:
0 1 2 1 0 0
7 1 3 2 1 1 1 2 1 0 1 0 0 0
这回答了你的问题吗?看看如文档中所述:Deques是堆栈和队列的泛化。为什么第二个输出不是:
0 1 0 0…
?我的解释如下:对于76,有7个间隔达到86,这高于76。对于3,只有1个间隔可以达到60,高于3。对于60,有3个间隔达到72,这比3高。以此类推…真的谢谢你。我尝试了你的代码,但仍然得到时间限制超过(TLE)错误。我认为问题在于你的答案仍然包含两个循环。