The obvious solution
Not sure if you know the obvious solution and just want to re-invent the wheel or if you are just not aware of this but you could just do :
>>> l = [1, 2, 3, 4, 5, 6]
>>> n = 2
>>> l[-n:] + l[:-n]
[5, 6, 1, 2, 3, 4]
The actual review : details
You have splitted your code into multiple functions, documented them, written the usual if __name-- == 'main':
test : this is already a pretty good beginning.
Also, pep8 only complies about some whitespaces not following the Python Style Guide (this is worth fixing it anyway).
However, here a few things that do not look good in your code and could easily be fixed :
- your code can be python 3 compliant by adding parenthesis in your calls to
print
.
- you have the same typo
rorate
in multiple places
list
is a bad name for a list as you can easily mix-up with the type
- your function and variable names does not follow the convention.
After fixing all this, you get something like :
def copy_digit(lst, index, item):
"""
Copy the item to the indexed location in the given list
"""
lst[index] = item
return lst
def rotate_list(lst, nb_rotate):
"""
Rotate List to right
"""
print("Function received {0},{1}".format(lst, nb_rotate))
for rotate in range(N):
last_item = lst[-1]
for i in range(len(lst) - 2, -1, -1):
item_to_shift = lst[i]
lst = copy_digit(lst, i + 1, item_to_shift)
lst[0] = last_item
print("Rotate once: {0}".format(lst))
return lst
if __name__ == '__main__':
"""
This program will rotate right the given list N no of times
"""
array = [1, 2, 3, 4, 5, 6]
N = 2
print("Rotate an array: ", array, "No of times: ", N)
final_list = rotate_list(array, N)
print("Rotated List: ", final_list)
A subtle bug
What if I was to call :
final_list = rotate_list(array, 2)
? Surprisingly enough, I'd get an error. I'll let you have a look at this because it is not very complicated.
Clearer interface for your functions
Your function copy_digit
updates the list and returns it. There is no real need for this as the caller would already have the initial list. Then you can just have :
def copy_digit(lst, index, item):
"""
Copy the item to the indexed location in the given list
"""
lst[index] = item
and
...
copy_digit(lst, i + 1, item_to_shift)
...
Of course, the need for a function seems a bit doubtful here. Let's inline this :
...
lst[i + 1] = item_to_shift
...
Then, it seems like the item_to_shift
variable is not really required anymore :
for i in range(len(lst) - 2, -1, -1):
lst[i + 1] = lst[i]
And more generally
In Programming Pearls (sorry I couldn't find the relevant full text), Jon Bentley describes different solutions to the problem. Some behind quite original and actually very easy to implement on top of being efficient. I'll let you google "programming pearls rotate" if you want to read more about this. It is defintly worth a read (and the whole book is too).