gpt4 book ai didi

python - 如何有效地左移一个元组?

转载 作者:行者123 更新时间:2023-11-28 19:36:07 25 4
gpt4 key购买 nike

我正在寻找一种左移元组的有效方法。

到目前为止我做了什么:

def leftShift(tup, n):
length = len(tup)
if length != 0:
n = n % length
else:
return tuple()
return tup[n:] + tup[0:n]

sample = (1,2,3,4)
sample2 = ()

print(leftShift(sample, 5)) #prints (2, 3, 4, 1)
print(leftShift(sample, 1)) #prints (2, 3, 4, 1)
print(leftShift(sample, 15)) #prints (4, 1, 2, 3)
print(leftShift(sample, 3)) #prints (4, 1, 2, 3)
print(leftShift(sample2, 4)) #prints ()

要移动的位置数作为第二个参数给出。

效率高吗?它可以用更 Pythonic 的方式编码吗?

然后告诉我,是不是...

length = len(tup)
if length != 0:
n = n % length

更有效率
if len(tup) != 0:
n = n % len(tup)

?

我的意思是,是 len(tup) O(1) 还是我应该记住它以备后用?

最佳答案

您所做的是绝对的微观优化,如果您不确切知道自己的目标是什么,那完全是在浪费时间。

您的代码的第一个版本可能更快,因为它使用的函数调用更少,但两者都很好。如果您真的很在意速度,您应该首先了解如何使用分析器和 timeit 模块。

len(tup) 需要常数时间。

也许你想要一个 deque哪个有旋转方法?

这里有一些替代方案:

def leftShift1(tup, n):
try:
n = n % len(tup)
except ZeroDivisionError:
return tuple()
return tup[n:] + tup[0:n]

def leftShift2(tup, n):
length = len(tup)
if length != 0:
n = n % length
else:
return tuple()
return tup[n:] + tup[0:n]

def leftShift3(tup, n):
if len(tup) != 0:
n = n % len(tup)
else:
return tuple()
return tup[n:] + tup[0:n]

def leftShift4(tup, n):
if tup:
n = n % len(tup)
else:
return tuple()
return tup[n:] + tup[0:n]

sample= tuple(range(10))

随机时间结果

D:\downloads>python -m timeit -s"from asd import *" "leftShift1(sample, 20)"
1000000 loops, best of 3: 0.472 usec per loop

D:\downloads>python -m timeit -s"from asd import *" "leftShift2(sample, 20)"
1000000 loops, best of 3: 0.533 usec per loop

D:\downloads>python -m timeit -s"from asd import *" "leftShift3(sample, 20)"
1000000 loops, best of 3: 0.582 usec per loop

D:\downloads>python -m timeit -s"from asd import *" "leftShift4(sample, 20)"
1000000 loops, best of 3: 0.474 usec per loop

所以:

  • 最 Pythonic 的代码(try .. exceptif tup:)是最快的。为此一定要喜欢 Python。
  • 您可以节省令人难以置信的 0.0000001 秒。

关于python - 如何有效地左移一个元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5299135/

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