William Merritt
William Merritt

Reputation: 439

Efficient way to rotate strings through slicing

The following program is designed to take a string, my_string = "Stackoverflow", and rotate it to the right based off a given integer 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"

Is this the most efficient way to perform this function? Space complexity wise I know its not favorable to create new variables. Can it be done without creating new variables without sacrificing readability? In place?

Upvotes: 0

Views: 218

Answers (4)

RudRocks05
RudRocks05

Reputation: 13

Yes you can

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

rotateString(2, "Stackoverflow")

Upvotes: 0

Alireza Afzal Aghaei
Alireza Afzal Aghaei

Reputation: 1235

Here is a comparison of suggested answers using Ipython timeit module:

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

Now Test using ipython:

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

OUTPUT:

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)

Upvotes: 2

Cory Nezin
Cory Nezin

Reputation: 1581

Python strings are immutable, so no you cannot do it without creating a new variable. If you really want to be space efficient, you could use a list of characters or if you want to be very efficient, a byte array

Upvotes: 0

Transhuman
Transhuman

Reputation: 3547

One way is using collections.deque

from collections import deque

my_string = "Stackoverflow"

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

Upvotes: 1

Related Questions