【问题标题】:Efficient way to rotate strings through slicing通过切片旋转字符串的有效方法
【发布时间】:2019-05-08 19:31:42
【问题描述】:

以下程序旨在获取一个字符串 my_string = "Stackoverflow",并根据给定整数 num 将其向右旋转。

def rotateString(n, arr):
    rotate_beginning = arr[0 : len(arr)-n] 
    rotate_end = arr[len(arr)-n : ]
    newStr = rotate_end + rotate_beginning
    print (newStr)


my_string = "Stackoverflow"
num = 2
rotate(num, my_string)


# prints "owStackoverfl"

这是执行此功能的最有效方式吗?空间复杂度方面,我知道创建新变量不利于。可以在不牺牲可读性的情况下创建新变量吗?到位?

【问题讨论】:

  • arr[-n:] + arr[:-n] 会更pythonic,也更高效。

标签: python string performance slice


【解决方案1】:

一种方法是使用collections.deque

from collections import deque

my_string = "Stackoverflow"

d = deque(my_string)
d.rotate(1)
print (''.join(d))
#wStackoverflo

【讨论】:

  • 真的比原来的解决方案更有效率吗?
【解决方案2】:

Python 字符串是不可变的,所以不创建新变量就无法做到这一点。如果你真的想节省空间,你可以使用一个字符列表,或者如果你想非常高效,byte array

【讨论】:

    【解决方案3】:

    以下是使用 Ipython timeit 模块的建议答案比较:

    from collections import deque
    
    def rotateString1(n, arr):
        rotate_beginning = arr[0 : len(arr)-n] 
        rotate_end = arr[len(arr)-n : ]
        newStr = rotate_end + rotate_beginning
        return newStr
    
    
    def rotateString2(n, arr):    
        d = deque(arr)
        d.rotate(n)
        return ''.join(d)
    
    def rotateString3(n, arr):   
        return arr[-n:]+arr[:-n]
    
    my_string = "Stackoverflow"
    num = 2
    

    现在使用 ipython 进行测试:

    %timeit rotateString1(num, my_string)
    %timeit rotateString2(num, my_string)
    %timeit rotateString3(num, my_string)
    

    输出:

    465 ns ± 11.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    968 ns ± 26.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    353 ns ± 3.38 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    

    【讨论】:

      【解决方案4】:

      是的,你可以

      def rotateString(n, arr):
         print (arr[len(arr)-n : ]+  arr[0 : len(arr)-n] )
      
      rotateString(2, "Stackoverflow")
      

      【讨论】:

        猜你喜欢
        • 2011-05-24
        • 1970-01-01
        • 2010-10-20
        • 2014-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-24
        • 2020-11-27
        相关资源
        最近更新 更多