codility Lesson2 CyclicRotation

CyclicRotation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).

The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.

Write a function:

def solution(A, K)

that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.

For example, given
A = [3, 8, 9, 7, 6]
K = 3

the function should return [9, 7, 6, 3, 8]. Three rotations were made:
[3, 8, 9, 7, 6] -[6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -[7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -[9, 7, 6, 3, 8]

For another example, given
A = [0, 0, 0]
K = 1

the function should return [0, 0, 0]

Given
A = [1, 2, 3, 4]
K = 4

the function should return [1, 2, 3, 4]

Assume that:

N and K are integers within the range [0..100];
each element of array A is an integer within the range [−1,000..1,000].

In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.
Copyright 2009–2019 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

방법

배열 A의 크기를 N으로 하였을 때 N의 요소들을 K만큼 옮기기 위하여 N의 요소들의 index값에 K를 더하여 해결
N의 inedx+K의 값이 N의 전체 길이보다 클 경우 0부터 증가시킴
위 방법을 그대로 사용 할 경우 반복이 많아짐
N의 길이가 5이고 K가 3이라고 할 경우 N[0]의 값은 N[3]이 되며 N[4]는 N[7]이 되어 0부터 다시 계산하면 N[2]가 됨
K의 값이 N의 길이보다 많이 클 경우를 생각하여 %연산을 이용
즉 본래 index+K의 값을 N의 길이로 나눈 나머지 값을 새로운 index로 사용
N[4]는 N[7]되고 7%5=2가 됨


코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import copy
def solution(A, K):
# write your code in Python 3.6

n = len(A)


#return [9, 7, 6, 3, 8].
result = copy.deepcopy(A)

if n==0 or K%n==0:
return A

else:
for i in range(n):
index = (i+K)%n
result[index] = A[i]
return result

pass

추가

오늘 python을 배운김에 python으로 작성해봄


결과

image

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×