Codility_2. Arrays - [Easy]CyclicRotation

HyeonKi Jo·2022년 7월 5일
0

Codility_Lesson

목록 보기
2/2
post-thumbnail

문제

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

  • A 리스트가 들어왔을 때, K만큼 오른쪽으로 시프트된 리스트를 반환하라

예시

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]

코드

def solution(A, K):			
    if A:					# A이 빈 리스트일때를 고려한다.
        K = -1 * (K%len(A))	# K를 -로해서 A[-3]이런식으로 리스트에 접근한다.

    arr = []				# 반환할 리스트 초기화

    for i in range(len(A)):	# 모든 A의 원소에 접근한다.
        arr.append(A[K])	# -K인덱스부터 접근한다.
        K+=1				# 점차 오른쪽으로 이동한다.

    return arr				# 새로 생성된 리스트 반환
profile
Talking Potato

0개의 댓글