以下程序旨在获取字符串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"
这是执行此功能的最有效方法吗?我知道空间复杂度不利于创建新变量。是否可以在不牺牲可读性的前提下创建新变量而完成?到位?
答案 0 :(得分:2)
以下是使用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)
答案 1 :(得分:1)
一种方法是使用collections.deque
from collections import deque
my_string = "Stackoverflow"
d = deque(my_string)
d.rotate(1)
print (''.join(d))
#wStackoverflo
答案 2 :(得分:0)
Python字符串是不可变的,因此不创建新变量就无法做到这一点。如果您确实想节省空间,可以使用一个字符列表,或者如果要非常节省空间,可以使用byte array
答案 3 :(得分:0)
是的
def rotateString(n, arr):
print (arr[len(arr)-n : ]+ arr[0 : len(arr)-n] )
rotateString(2, "Stackoverflow")