我正在尝试创建将使用给定整数的代码,然后输出一组整数,所有这些都是输入整数的数字的旋转。
因此,如果我输入“ 197”,则输出应为“ 197”,“ 971”和“ 791”。
但是,当我尝试时:
def rotation(n):
rotations = set()
for i in range( len( str(n) ) ):
n = int( str(n)[i:] + str(n)[:i] )
rotations.add(n)
使用输入“ 197”,它仅返回“ 197”,“ 971”,而不返回“ 791”。
为什么会这样?
答案 0 :(得分:2)
您快到了。除非您要在每次迭代中擦除输入n。使用另一个变量名。
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))
我会使用集合理解来写成这样:
def rotation(number):
str_number = str(number)
return {
int( str_number[i:] + str_number[:i] )
for i in range(len(str_number))
}
@Henry Woody的解决方案2也很好。而不是在每次迭代中将输入字符串旋转i
,而是从上一次迭代中旋转1
。
答案 1 :(得分:1)
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