I want to start by saying thank you for the help first.
I am tackling the cyclic rotation problem where you have to shift the contents of an list/array to the right and effectively wrapping the elements around so for example:
For example, given
JavaScript
x
3
1
A = [3, 8, 9, 7, 6]
2
K = 3
3
the function should return [9, 7, 6, 3, 8]. Three rotations were made:
JavaScript
1
4
1
[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
2
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
3
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
4
my code is as follows:
JavaScript
1
12
12
1
def solution(A, K):
2
new_list = []
3
first_index = 0
4
for i in range(0, K):
5
for num in range(0, len(A) - 1):
6
new_list.insert(0, A.pop())
7
print('new list {}'.format(new_list))
8
print('old list {}'.format(A))
9
if len(new_list) == 3:
10
new_list.insert(len(new_list), A.pop(first_index))
11
print(new_list)
12
after 3 rotations I get the list as A = [8, 9, 7, 6, 3] so to me it appears to place the last element from A to the front of the new_list.
So any help or points in the right direction would be helpful thank you again.
Advertisement
Answer
So I realised I only had to loop around K times and check for an empty list. And what I got in the end is:
JavaScript
1
7
1
def solution(A, K):
2
for i in range(0, K): # will perform K iterations of the below code
3
if A == []: # check if list is empty
4
return A # return A if A is the empty list
5
A.insert(0, A.pop()) # inserts at the first index of A the last element of A
6
return A # will return the list A
7