繁体   English   中英

Python程序因超时而终止

[英]Python program Terminated due to timeout

我正在尝试解决来自hackerrank的问题,当我提交解决方案时,出现错误消息“由于超时而终止”。

请检查代码并建议我如何进行优化。

声明:您的序列为空,将被查询。 每个查询都是以下三种类型之一:

1 x-将元素x推入堆栈。 2-删除出现在堆栈顶部的元素。 3-打印堆栈中的最大元素。

输入格式

输入的第一行包含一个整数。 接下来的每一行都包含上述查询。 (保证每个查询都是有效的。)

输出格式

对于每个类型查询,在新行中打印堆栈中的最大元素。

样本输入

10 1 97 2 1 20 2 1 26 1 20 2 3 1 91 3

样本输出

26 91

我的代码:

n = int(input())
stack = []

for i in range(n):
     l = list(map(int,input().split(" ")))
     if l[0] == 1:
        stack.append(l[1])
    elif l[0] == 2:
        stack.pop()
    elif l[0] == 3:
        print(max(stack))  

如果我看对了,请指定计数器i,但不要使用它。 如果您的第一个输入不是明显不是的命令之一,则不会产生任何输出或任何结果。

n = int(input())
stack = []

for i in range(n):
     l = list(map(int,input().split(" ")))
     if l[i] == 1:
        stack.append(l[i+1])
    elif l[i] == 2:
        stack.pop()
    elif l[i] == 3:
        print(max(stack))  

这是具有预期输出的正确输入。

"""
    proper input format for you problem
    10
    1 97
    2
    1 20
    2
    1 26
    1 20
    2
    3
    1 91
    3
    """

    n = int(raw_input())
        stack = []
        while n > 0:
            # read the option here it may be of form 1 x or 2 or 3
            option = map(int,raw_input().split())
            # if it has two elements that means it was of form 1 x,
            # so, push the second element on stack (stack[1])
            if len(option) > 1:
                stack.append(option[1] )
            else:
                # if option is 2 there will only be one element 
                # in option ( which is option[0]
                # so, remove from top of stack
                if option[0] == 2:
                    del stack[-1]
                else:
                    print max(stack)
            n = n-1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM