파이썬 넘파이에서 shuffle와 permutation의 역할차이

조회수 4538회

파이썬 넘파이에서 shuffle와 permutation의 역할이 무작위로 배열을 섞는 것이 잖아요 그런데 이 둘의 차이가 무엇인지 궁금합니다.

1 답변

  • 사실 permutation 은 순열중에 하나를 리턴하는 것인데 어차피 shuffle 의 결과는 순열중에 하나이기 때문에 결과 자체는 같다고 할 수 있습니다.

    permutation 도움말(https://het.as.utexas.edu/HET/Software/Numpy/reference/generated/numpy.random.permutation.html ) 대로 중요한 차이점은 permutation 은 array를 복사하여 리턴한다는 것 입니다. 즉 원본은 유지가 됩니다. 반면에 shffle 은 원본을 바꿉니다.

    numpy 가 cython으로 코딩(.pyx)되어 있는데 실제 코드를 보면 배열을 복사후 shuffle 을 호출합니다.

    def permutation(self, object x):
            if isinstance(x, (int, np.integer)):
                arr = np.arange(x)
                self.shuffle(arr)
                return arr
    
            arr = np.asarray(x)
    
            # shuffle has fast-path for 1-d
            if arr.ndim == 1:
                # Return a copy if same memory
                if np.may_share_memory(arr, x):
                    arr = np.array(arr)
                self.shuffle(arr)
                return arr
    
            # Shuffle index array, dtype to ensure fast path
            idx = np.arange(arr.shape[0], dtype=np.intp)
            self.shuffle(idx)
            return arr[idx]
    
    In [6]: ARR = [1, 2, 3]                                                         
    
    In [7]: np.random.permutation(ARR)                                              
    Out[7]: array([1, 3, 2])
    
    In [8]: ARR                                                                     
    Out[8]: [1, 2, 3]
    
    In [9]: np.random.shuffle(ARR)                                                  
    
    In [10]: ARR                                                                    
    Out[10]: [1, 3, 2]
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)