Reputation: 109
Given string is "abc" then it should print out "abc", "bca", "cba"
My approach: find length of the given string and rotate them till length
def possible_rotation():
a = "abc"
b = len(a)
for i in range (b-1):
c = a[:i] + a[i:]
print c
Above code simply prints abc, abc. Any idea what am I missing here?
Upvotes: 1
Views: 3195
Reputation: 11163
Two things:
Firstly, as already pointed out in the comments, you should iterate over range(b)
instead of range(b-1)
. In general, range(b)
is equal to [0, 1, ..., b-1]
, so in your example that would be [0, 1, 2]
.
Secondly, you switched around the two terms, it should be: a[i:] + a[:i]
.
Upvotes: -1
Reputation: 217
This is what I did. I used a deque
, A class in collections and then used the rotate function like this
from collections import deque
string = 'abc'
for i in range(len(string)):
c = deque(string)
c.rotate(i)
print ''.join(list(c))
And gives me this output.
abc
cab
bca
What it does. It creates a deque
object, A double ended queue object, which has a method rotate, rotate takes the number of steps to rotate and returns the objects shifted to the right with the number of steps kinda like rshift
in binary operations. Through the loops it shifts ad produces a deque object that I convert to list and finally to a string.
Hope this helps
Upvotes: 1
Reputation: 12515
This looks to be homework, but here's a solution using the built-in collections.deque
:
from collections import deque
def possible_rotations(string):
rotated = deque(string)
joined = None
while joined != string:
rotated.rotate(1)
joined = ''.join(x for x in rotated)
print(joined)
Test it out:
>>> print(possible_rotations('abc'))
cab
bca
abc
Upvotes: -1
Reputation: 93
No need to do (b-1),You simply do it by:
def possible_rotation():
a = "abc"
for i in range(0,len(a)):
strng = a[i:]+a[:i]
print strng
possible_rotation()
`
Upvotes: -1
Reputation: 4985
for i in range(b):
print(a[i:] + a[:i])
0 - [a,b,c] + []
1 - [b,c] + [a]
2 - [c ] + [a,b]
swap the lists
Upvotes: 0
Reputation: 500167
You have two errors:
range(b-1)
should be range(b)
;a[:i] + a[i:]
should be a[i:] + a[:i]
.Upvotes: 2
Reputation: 67968
def possible_rotation():
a = "abc"
b = len(a)
for i in range (b):
c = a[i:]+a[:i]
print c
possible_rotation()
Output:
abc
bca
cab
You have 2 issues.The range issue and the rotation logic.it should be a[i:]+a[:i]
not the other way round.For range range(b-1) should be range(b)
Upvotes: 2