gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:13:38 24 4
gpt4 key购买 nike

考虑一个列表 (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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com