끄적끄적
Codility Lesson2 - CyclicRotation 본문
Codility Lesson2 - CyclicRotation
https://app.codility.com/demo/results/trainingX872UE-GT9/
Test results - Codility
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,
app.codility.com
문제
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.
정답1
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def rotation(A):
length = len(A)
newA = [0] * length
for i in range(1,length):
newA[i]= A[i-1]
newA[0]=A[length-1]
return newA
def solution(A, K):
# Implement your solution here
for j in range(K):
newA= rotation(A)
A=newA
return newA
결과1


-> 원소가 없을 때, K가 0일 때를 고려하지 않음. A의 갯수만큼 []*len(A)하기 때문에 K가 0일 때를 언급 하지 않으면 [0]만 반환
정답-Retry
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def rotation(A):
length = len(A)
newA = [0] * length
for i in range(1,length):
newA[i]= A[i-1]
newA[0]=A[length-1]
return newA
def solution(A, K):
# Implement your solution here
length = len(A)
newA = [0] * length
if K==0:
newA=A
elif length >=1:
for j in range(K):
newA= rotation(A)
A=newA
return newA
결과-Retry

'Codility Lessons' 카테고리의 다른 글
| Cobility Lesson3 - TapeEquilibrium (0) | 2023.09.14 |
|---|---|
| Cobility Lesson3 - PermMissingElem (0) | 2023.09.13 |
| Codility Lesson3 - FrogJmp (0) | 2023.09.13 |
| Codility Lesson2 - OddOccurrencesInArray (0) | 2023.09.13 |
| Codility Lesson1 - Iterations (0) | 2023.09.12 |