如何有效地左移元组?
我正在寻找一种有效的方法来左移元组。
到目前为止我所做的:
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) 还是我应该记住它以供以后使用?
I'm looking for an efficient way to left-shift a tuple.
What I've done so far:
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 ()
The number of places to shift is given as the second argument.
Is it efficient? Can it be coded in more Pythonic way?
And tell me, is it...
length = len(tup)
if length != 0:
n = n % length
more efficient than
if len(tup) != 0:
n = n % len(tup)
?
I mean, is len(tup)
O(1) or should I remember it for later usage?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所做的绝对是微观优化,如果您不确切知道自己的目标是什么,那完全是浪费时间。
代码的第一个版本可能更快,因为它使用了更少的函数调用,但两者都很好。如果您真的关心速度,您应该首先弄清楚如何使用分析器和 timeit 模块。
len(tup)
需要常数时间。也许您想要一个具有旋转方法的 deque ?
这里有一些替代方案:
随机 timeit 结果
所以:
try .. except
和if tup:
)是最快的。为此我一定会喜欢Python。What you're doing is absolute micro-optimization, which is a total waste of time if you don't know exactly what you're aiming for.
The first version of you code is probably faster because it uses one less function call, but both are fine. If you really care about speed you should figure out how to use a profiler and the timeit module first.
len(tup)
takes constant time.Maybe you want a deque which has a rotate method?
Here are some alternatives:
random timeit results
So:
try .. except
andif tup:
) is the fastest. Gotta love Python for that.更简洁一点
A little more tersely