본문 바로가기
Problem Solving/Codility

[Python] 2.1. CyclicRotation

by 부르르 2021. 3. 6.

https://app.codility.com/programmers/lessons/2-arrays/

 

2. Arrays lesson - Learn to Code - Codility

Rotate an array to the right by a given number of steps.

app.codility.com


빈 배열이 들어올 경우에는 그대로 리턴한다

빈 배열이 아닌 경우 입력값 K에 대한 나머지를 구하고  다음 인덱스 값을 계산해준다

만약 다음 인덱스 값이 음수 일 경우, 배열의 크기를 더해서 인덱스 값을 보정해준다.

def solution(A, K): ​​​​if len(A) == 0: ​​​​​​​​return A ​​​​rotate = K % len(A) ​​​​answer = [] ​​​​for idx in range(len(A)): ​​​​​​​​next_idx = idx - rotate ​​​​​​​​if next_idx < 0: ​​​​​​​​​​​​next_idx += len(A) ​​​​​​​​answer.append(A[next_idx]) ​​​​return answer
728x90
반응형

'Problem Solving > Codility' 카테고리의 다른 글

[Python] 3.3. TapeEquilibrium  (0) 2021.03.11
[Python] 3.2. PermMissingElem  (0) 2021.03.11
[Python] 3.1. FrogJmp  (0) 2021.03.07
[Python] 2.2. OddOccurrencesInArray  (0) 2021.03.07
[Python] 1.1. BinaryGap  (0) 2021.03.06

댓글