Home > Net >  program to rotate list of numbers until all numbers have moved back to origioal position
program to rotate list of numbers until all numbers have moved back to origioal position

Time:05-09

I'm trying to write a program were given a list, the program reads through a list and rotates the numbers in the list one position for each interaction until the numbers reach starting position.

example of required output:

list : 1 2 3 4
[1,2,3,4]
[2,3,4,1]
[3,4,1,2]
[4,1,2,3]
[1,2,3,4]

I have written code to do this but it's not efficient and doesn't print how I would like it.

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(1234))

the output for this code is

{1234, 4123, 3412, 2341}

if anyone could help me out with this, would be greatly appreciated.

CodePudding user response:

It's not clear why you're operating on the number 1234 when you want to operate on the list [1, 2, 3, 4], or why your function is returning a set when you want the output to contain a repeated element. All this does is make the problem more complicated.

Just have the function take the original list and print each rotation:

>>> def rotation(nums):
...     for i in range(len(nums) 1):
...         print(nums[i:]   nums[:i])
...
>>> rotation([1, 2, 3, 4])
[1, 2, 3, 4]
[2, 3, 4, 1]
[3, 4, 1, 2]
[4, 1, 2, 3]
[1, 2, 3, 4]

CodePudding user response:

Do this,

def rotation(series):
  for i in range(len(series)   1):
    print(series)
    series = series[1:]   series[:1]

rotation([1,2,3,4])
[1, 2, 3, 4]
[2, 3, 4, 1]
[3, 4, 1, 2]
[4, 1, 2, 3]
[1, 2, 3, 4]
  • Related