You can use modular arithmetic for reducing number of shifts for large numbers:
s = "abcd"
leftshift = 544645655 # using left shift as per sample output in question
# for rightshift, use negative number
N = leftshift % len(s) # reduce shifts using modulo, explained below
print((s+s)[N:N+len(s)])
You can also use: print(s[N:] + s[:N])
for the print, as other answers show.
Output:
dabc
Explanation:
For numbers greater than 4 (string length), the pattern just repeats. You can use modular arithmetic to convert it to a number within [0,3].
a % b
below denotes the modulus operation (It is equivalent to remainder
of division a / b
for positive numbers)
abcd # leftshift = 0 (0 % 4 = 0) [leftshift % len(s) = N]
bcda # leftshift = 1 (1 % 4 = 1)
cdab # leftshift = 2 (2 % 4 = 2)
dabc # leftshift = 3 (3 % 4 = 3)
abcd # leftshift = 4 (4 % 4 = 0)
bcda # leftshift = 5 (5 % 4 = 1)
cdab # leftshift = 6 (6 % 4 = 2)
dabc # leftshift = 7 (7 % 4 = 3)
abcd # leftshift = 8 (8 % 4 = 0)
^ repeating pattern ^ you only have to shift by this number
So to shift by 544645655
, we only have to shift by 544645655 % len(s) = 3
>>> s = "abcd"
>>> (s+s)
'abcdabcd'
We take the slice of length len(s) at position 0 like this:
'abcdabcd'
^^^^
>>> (s+s)[:len(s)]
'abcd'
Now all we need is move this slice like this:
abcdabcd
^^^^
>>> (s+s)[3:3+len(s)] # 3 is the leftshift count
'dabc'
Put in the modular expression N = leftshift % len(s)
instead of 3:
>>> leftshift = 5
>>> N = leftshift % len(s) # N = 1
>>> (s+s)[N:N+len(s)]
'bcda'