코딜리티 | lesson2 - Arrays : CyclicRotation (python)

cun·2024년 1월 27일
0

Codility

목록 보기
2/12
post-thumbnail

💻lesson2 - CyclicRotation

1. 문제

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.

2. 문제 접근

돌린다고 생각하기보다 맨 뒷자리를 앞으로 이동시키는 것이 이 문제를 해결하는 포인트인 듯 하다.

  1. 맨 뒷자리를 변수에 저장한 후 pop으로 제거한다.
  2. 리스트를 reverse한 다음 맨 뒷자리를 저장한 변수를 append한다.
  3. 다시 reverse하여 원래 배열대로 되돌린다.
  4. K 숫자 만큼 반복한다.

으로 코드 작성을 진행하였다.

3. 풀이 - python

def solution(A, K):
    n = len(A)
    for i in range(K):
        last_num = A[n-1]
        A.pop()
        A.reverse()
        A.append(last_num)
        A.reverse()
    return A

4. 결과

오늘은 87%... 아무래도 놓친 부분이 있었나보다.

코딜리티는 친절하게도 어디에서 에러가 나는지 런타임이 나는지 분석해준다.
심지어 코드 작성 진행하는 것조차 녹화해준다. (과다한 친절...ㅎㅎ;^;)
하지만 이런 친절 덕분에 어디에서 틀렸는지 알 수 있었다.

Analysis summary
The following issues have been detected: runtime errors.
For example, for the input ([], 1) the solution terminated unexpectedly.

그렇군! 빈 배열에서 런타임 에러가 발생한다는 것이다!
여러 경우의 수를 고려해서 코드를 짜도록 하자

5. 마무리

코딩을 하면 할수록 약간 추리하는 기분이 든다. 조건을 잘 따지고 모든 상황의 경우의 수를 고려하며 성공하게 되면 사건을 하나 처리한 느낌이랄까...ㅎㅎ
문제를 풀면서 내가 조건을 너무 안일하게 보고 고려를 하지 않았던 같다.
조건에서도 조차 k와 배열 A둘다 0에서 100사이 값이라고 정확히 명시해있는데 말이다.
이런 부분까지 고려해야 진정한 개발자로 성장할 수 있다는 거겠지...
다음 문제를 풀때는 조건 잘 고려해가면서 풀어보자~@!

그리고 이 문제는 나중에 sorting 공부할때 연습겸 풀기로

profile
꾸준하게!

0개의 댓글