Reputation: 3
I want to rotate a word to the right, so that every letter has passed.
What I tried to do is make a function. It looks like this (yeah yeah ik lmao):
word = "Abobus";
length = len(word);
n = 1;
def rotation():
for i in range(length + 1):
c = word[0 : length-n] + word[length-n:]
print(c)
rotation();
I needed the output to be:
Abobus sAbobu usAbob busAbo obusAb bobusA Abobus
Instead, the output was:
Abobus Abobus Abobus Abobus Abobus Abobus Abobus
What exactly am I doing wrong?
Upvotes: 0
Views: 91
Reputation: 1537
Another option (which has potential to be more efficient when working with large inputs) is to use collections.deque
which is optimized for such operations:
import collections
word = "Abobus"
word_as_deque = collections.deque("Abobus")
for _ in word:
print("".join(word_as_deque))
word_as_deque.appendleft(word_as_deque.pop())
## output:
Abobus
sAbobu
usAbob
busAbo
obusAb
bobusA
Upvotes: 1
Reputation: 36598
You are splitting at an index in word
, but then just putting the two pieces back together. Also, you are not use i
to move the split index.
def rotation(word):
length = len(word)
for i in range(length):
c = word[-i:] + word[:-i]
print(c)
rotation('Abobus')
# prints:
Abobus
sAbobu
usAbob
busAbo
obusAb
bobusA
Upvotes: 1
Reputation: 194
I changed the logic of the program you have written.. This will work
word = "Abobus"
def rotation():
print(word)
n = len(word) - 1
for _ in range(len(word)):
c = word[n:] + word[0: n]
n -= 1
print(c)
rotation()
Upvotes: 0