Mac*_*rko 2 python tuples shift
我正在寻找一种左移元组的有效方法.
到目前为止我做了什么:
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 ()
Run Code Online (Sandbox Code Playgroud)
移位的位数作为第二个参数给出.
它有效吗?它可以用更多Pythonic方式编码吗?
告诉我,是吗......
length = len(tup)
if length != 0:
n = n % length
Run Code Online (Sandbox Code Playgroud)
效率更高
if len(tup) != 0:
n = n % len(tup)
Run Code Online (Sandbox Code Playgroud)
?
我的意思是,是len(tup)O(1)还是我应该记住它供以后使用?
你所做的是绝对的微观优化,如果你不确切地知道你的目标是什么,这是完全浪费时间.
您的代码的第一个版本可能更快,因为它使用少一个函数调用,但两者都很好.如果你真的关心速度,你应该首先弄清楚如何使用分析器和timeit模块.
len(tup) 需要不断的时间.
也许你想要一个有旋转方法的双端队列?
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))
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
所以:
try .. except和if tup:)是最快的.一定要喜欢Python.更简洁一点
def leftShift(tup, n):
if not tup or not n:
return tup
n %= len(tup)
return tup[n:] + tup[:n]
Run Code Online (Sandbox Code Playgroud)