Generating circular shifts / reduced Latin Squares in Python

前端 未结 7 1271
旧时难觅i
旧时难觅i 2020-12-31 19:38

Was just wondering what\'s the most efficient way of generating all the circular shifts of a list in Python. In either direction. For example, given a list [1, 2, 3, 4

7条回答
  •  心在旅途
    2020-12-31 20:14

    This will be my solution.

    #given list
    a = [1,2,3,4]
    #looping through list
    for i in xrange(len(a)):
        #inserting last element at the starting
        a.insert(0,a[len(a)-1])
        #removing the last element
        a = a[:len(a)-1]
        #printing if you want to
        print a
    

    This will output the following:

    [4, 1, 2, 3]
    [3, 4, 1, 2]
    [2, 3, 4, 1]
    [1, 2, 3, 4]
    

    You can also use pop instead of using list slicing but the problem with pop is that it will return something.

    Also the above code will work for any length of list. I have not checked for performance of the code. I am assuming that it will work better.

    You should have a look at Python docs for getting a good understanding of List slicing.

提交回复
热议问题