본문 바로가기
코딩/코딜리티 문제 풀기

코딜리티 2-1 CyclicRotation (python)

by -솔솔- 2020. 11. 8.
반응형

코딜리티!

 

1째 시도: correctness와 performace 둘 다 100%긴 한데 코드가 지저분하다.

def solution(A, K): # given an array A consisting of N integers and an integer K, returns the array A rotated K times.
    N = len(A)
    
    if N<2:
        return A
     
    if K>=N:
        K = K%N       
        
    B=[]
    
    for i in range(0, K):
        B.append(A[N-K+i])
        
    for j in range(0, N-K):
         B.append(A[j])
         
    return B

 

2째 시도: python의 list slicing 방법을 알게되어 적용했다. 좀 더 깔끔하게 코딩했다.

def solution(A, K): # given an array A consisting of N integers and an integer K, returns the array A rotated K times.
    N = len(A)
    
    if N<2:
        return A
     
    if K>=N:
        K = K%N       
        
    return A[N-K:]+A[:N-K]

 

아직까지는 간단한 문제인 것 같다~~

댓글