2

What are the logics possible to loop a string into a grid?

For example if I wanted 'water' to print

water
aterw
terwa
erwat
rwate

I was trying something along the lines of,

word = 'water'
for number, letter in enumerate(word):
    if number < len(word):
        print a + word[1:] + word[:1]

I do not comprehend how i can achieve this as you can see from my attempt. Thanks for any help.

3 Answers 3

5
In [2]: word = 'water'
   ...: for i in range(len(word)):
   ...:     print(word[i:] + word[:i])
water
aterw
terwa
erwat
rwate

The i loops over all possible indexes, takes the suffix starting at that index and prepends it to the string, obtaining all possible rotations.

Sign up to request clarification or add additional context in comments.

Comments

5

You can do

word = 'water'
for i in xrange(len(word)):
   print word[i:] + word[:i]

Comments

4

Use collections.deque, it has a rotate method that will do your job.

Rotate the deque n steps to the right. If n is negative, rotate to the left. Rotating one step to the right is equivalent to: d.appendleft(d.pop())

Demo:

from collections import deque
d = deque('water')
for _ in xrange(len(d)):
    print ''.join(d)
    d.rotate(-1)

output:

water
aterw
terwa
erwat
rwate

4 Comments

did not know you could do this! +1 for the discovery of deque :-)
This is kinda heavyweight for an OP that's trying to get slicing down. +/- 0 as I'm not sure if the answer should target the level of the question.
+1 for efficiency! To match the OP expected output you should swap rotate and print lines and use -1 as "step". -0 for the complexity of the answer(the OP seem to be completely new to python and programming...)
@Bakuriu Fixed the output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.