gpt4 book ai didi

python - 如何让这个运行 'faster'?或者这是正确的术语吗?

转载 作者:行者123 更新时间:2023-12-01 08:09:57 27 4
gpt4 key购买 nike

我是 python 新手,我为 Hackerrank 问题提交了此代码 Arrays and Simple Queries ,但对于大量测试用例,程序“由于超时而终止”。我怎样才能提高效率?

我已将主要交换功能粘贴在下面。(重复M次)

temp = input()
temp = temp.split(" ")
i = int(temp[1])-1
j = int(temp[2])-1
rep = (i-1)+1

if(temp[0]=='1') :
rep = (i-1)+1
while(i<=j) :
count = i-1
ex1 = count
ex2 = i
for k in range(0,rep) :
arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
ex1 = ex1-1
ex2 = ex2-1
i = i+1
else :
rep = (N-(j+1))
while(j>=i) :
count = j+1
ex1 = count
ex2 = j
for k in range(0,rep) :
arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
ex1 = ex1+1
ex2 = ex2+1
j=j-1

最佳答案

您可以尝试简单地连接切片,而不是使用许多循环:

def query(lst, t, start, end):
# Convert to proper zero-indexed index
start -= 1

if t == '1':
return lst[start:end] + lst[:start] + lst[end:]
elif t == '2':
return lst[:start] + lst[end:] + lst[start:end]


# Get the input however you want
N, M = map(int, input().split())
arr = list(map(int, input().split()))
assert len(arr) == N

for _ in range(M):
t, start, end = input().split()
arr = query(arr, t, int(start), int(end))

print(abs(arr[0] - arr[N - 1]))
print(*arr)

输入:

8 4
1 2 3 4 5 6 7 8
1 2 4
2 3 5
1 4 7
2 1 4

输出:

1
2 3 6 5 7 8 4 1

关于python - 如何让这个运行 'faster'?或者这是正确的术语吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55321002/

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