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

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)还是我应该记住它供以后使用?

Joc*_*zel 9

你所做的是绝对的微观优化,如果你不确切地知道你的目标是什么,这是完全浪费时间.

您的代码的第一个版本可能更快,因为它使用少一个函数调用,但两者都很好.如果你真的关心速度,你应该首先弄清楚如何使用分析器和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)

所以:

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


Pau*_*McG 6

更简洁一点

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)