Reputation: 35
I'm trying to create code that will take a given integer, then output a set of integers, all of which are rotations of digits of the input integer.
Thus, if I inputted '197', the output should be '197', '971', and '791'.
However, when I try:
def rotation(n):
rotations = set()
for i in range( len( str(n) ) ):
n = int( str(n)[i:] + str(n)[:i] )
rotations.add(n)
with the input '197', it only returns '197', '971', yet NOT '791'.
Why is this happening?
Upvotes: 2
Views: 4116
Reputation: 15652
The way you have your code structured does duplicate rotation because you reassign n
on each step of the loop and use the iteration variable i
in your slices.
So the process in the loop from your example is:
i = 0
n = 197
and the rotation logic does nothing with i = 0
so you add 197
to rotationsi = 1
n = 197
, and rotation logic makes n = 971
and you add that to rotations
.i = 2
n = 971
, and the rotation logic slices from index 2
, but n
has already been rotated so we have n = 197
again, which is added to rotations
(and removed since rotations
is a set). Basically n
has already been rotated forward, and now it is being rotated forward 2 steps (back to the initial value and skipping over n = 719
)To fix this you can either:
1. Keep n
at its initial value and on each step rotate n
the full amount (i
) and add that to rotation
without modifying n
. Like so:
def rotation(n):
rotations = set()
for i in range( len( str(n) ) ):
rotations.add(int( str(n)[i:] + str(n)[:i] ))
return rotations
2. Rotate n
forward on each step, but only rotate it forward one position each time. Like so:
def rotation(n):
rotations = set()
for i in range( len( str(n) ) ):
n = int( str(n)[1:] + str(n)[:1] )
rotations.add(n)
return rotations
Upvotes: 1
Reputation: 14664
You're almost there. Except you're erasing the input n at each iteration. Use another variable name.
def rotation(n):
rotations = set()
for i in range( len( str(n) ) ):
m = int( str(n)[i:] + str(n)[:i] )
rotations.add(m)
return rotations
print(rotation(197))
I would write it more like this, using a set comprehension:
def rotation(number):
str_number = str(number)
return {
int( str_number[i:] + str_number[:i] )
for i in range(len(str_number))
}
Solution 2 by @Henry Woody is nice too. Rather than rotate input string by i
at each iteration, rotate by 1
from last iteration.
Upvotes: 4