Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading