【问题标题】:How to implement stack in python?如何在python中实现堆栈?
【发布时间】:2020-04-11 00:45:13
【问题描述】:

这个问题可能用到了python中栈的概念。 我的代码如下,但总是出现 Time Limit Exceed (TLE) 错误。 我认为问题是由于两个循环,我设计的算法太慢了。 我想知道如何实现堆栈的概念并在这个问题中只使用一个循环。请指导我并帮我修改代码,非常感谢。

输入:包括一行,包含多个整数,代表每次的得分,数字之间用空格隔开

输出:包括一行,包含多个整数,表示每个分数增加时的间隔频率(如果分数不增加,则返回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

【问题讨论】:

  • 这能回答你的问题吗? Implementing Stack with Python
  • collections.deque。如文档中所述:双端队列是堆栈和队列的概括
  • 为什么第二个输出不是:0 1 0 0 ...?
  • 我的解释如下,对于76,有7个区间达到86,高于76。对于3,只有1个区间达到60,高于3。对于60 ,有3个区间达到72,高于3.以此类推...

标签: python data-structures stack


【解决方案1】:

您实际上可以使用带有一些理解的切片来做到这一点,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 如果该值高于 score 则获取第一个值在 nums 中的索引,否则默认为0

因此,您需要代替cal_interval 做的就是打印get_intervals 加入的结果:

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 

【讨论】:

  • 真的谢谢你。我尝试了您的代码,但仍然出现 Time Limit Exceed (TLE) 错误。我认为问题在于您的答案仍然包含两个循环。
【解决方案2】:
def stack():
    while(f==1):
        print("1. Push\n2. Pop\n3. Peek\n4. Traverse\n5. Quit")
        print("Enter any input: ")
        a = input()
        if a != '':
            a = int(a)
        switch(a)

def switch(a):
    global top
    if a == 1:
        print("Enter the Element To push")
        b = input()
        print(top)
        top += 1
        ar.append(b)
        print(b,"item was Pushed")
    elif a == 2:
        poped()
        print("item was Poped")
    elif a == 3:
        c = ar[top]
        print("Peek value is:",c)
    elif a == 4:
        print("Traversing all items")
        for i in ar:
            print(i)
    elif a ==5:
        print("Quit")
        global f
        f=2
    else:
        print("Invalid Value")


def poped():
    if top == -1:
        print("Stack is Empty /  Pop not performed")
    else:
        ar.pop()
        top -= 1

# Driver Code
f = 1
top = -1
ar = []
stack()

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 2010-09-22
    • 2015-09-22
    • 2021-11-16
    • 2021-06-24
    • 2013-12-18
    • 1970-01-01
    • 2013-01-25
    相关资源
    最近更新 更多