python-3.x - Hackerrank 列出问题 ~ 标准测试用例有效但其他无效

标签 python-3.x list

考虑一个列表 (list = [])。您可以执行以下命令:

insert i e: Insert integer e at position .
print: Print the list.
remove e: Delete the first occurrence of integer e.
append e: Insert integer e at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.

初始化您的列表并读入后面跟着命令行的值,其中每个命令都是上面列出的类型。按顺序遍历每个命令并在您的列表上执行相应的操作。

示例输入:

12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print

我的代码:

import sys

if __name__ == '__main__':
    N = int(input())

my_list = []
inputs  = []

for line in sys.stdin:
    inputs.append(line)

for item in inputs:
    if item[0:5] == 'print':
        print(my_list)
    elif item[0:2] == 'in':
        inserts = [s for s in item.split()][1:3]
        inserts = list(map(int, inserts))
        my_list.insert(inserts[0], inserts[1])
    elif item[0:3] == 'rem':
        inserts = list(map(int, [s for s in item.split()][1]))
        my_list.remove(inserts[0])
    elif item[0:2] == 'ap':
        inserts = list(map(int, [s for s in item.split()][1]))
        my_list.append(inserts[0])
    elif item[0:4] == 'sort':
        my_list.sort()
    elif item[0:3] == 'pop':
        my_list.pop()
    elif item[0:7] == 'reverse':
        my_list.reverse()

我不确定为什么我的代码在提交后没有获得批准。在他们提供的这个测试用例中,我的代码通过了。 预期输出如下:

[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]

非常感谢您的帮助!

最佳答案

if __name__ == '__main__':
    N = int(input())
    m=list()
    for i in range(N):
       method,*l=input().split()
       k=list(map(int,l))
       if len(k)==2:
          q=[k[0]]
          w=[k[1]]
       elif len(k)==1:
          q=[k[0]]
       if method =='insert':
          m.insert(q[0],w[0])
       elif method == 'append':
          m.append(q[0])
       elif  method == 'remove':
          m.remove(q[0])
       elif method =='print':
          print(m)
       elif method == 'reverse':
          m.reverse()
       elif method =='pop':
          m.pop()
       elif method == 'sort':
          m.sort()

关于python-3.x - Hackerrank 列出问题 ~ 标准测试用例有效但其他无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55861077/

相关文章:

python - 多索引 Pandas 数据框上的值错误

list - 如果嵌套列表有 1 个元素,如何删除 Scheme 中嵌套列表中的括号?

list - 从类型列表haskell中删除类型

python - 列表的最大值(字符串项)

Python3 - 如何在 pygame 混音器中更改声音的音量

python - 如何创建一个在后台运行并对键盘输入使用react的 Python 脚本?

Python时间表 "Time is freezing"

Python:将列表的批处理元素放入预定义的组中

R:pi[[j]] 中的错误:下标越界——数据帧列表上的 rbind

python - 在测试期间抑制日志