Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python – 문장에서 단어의 가능한 모든 순열 생성하기

문장 속 단어들의 가능한 모든 순열(permutation)을 생성해야 하는 경우, 별도의 함수를 정의하여 처리할 수 있습니다. 이 함수는 문자열을 반복(iteration)하면서 조건에 따라 결과를 화면에 출력합니다. Python에서는 표준 라이브러리인 itertoolspermutations 클래스를 활용하면 간단하게 구현할 수 있습니다.

예제

아래는 이를 구현한 예시 코드입니다.

from itertools import permutations

def calculate_permutations(my_string):
    my_list = list(my_string.split())
    permutes = permutations(my_list)
    for i in permutes:
        permute_list = list(i)
        for j in permute_list:
            print(j)
        print()

my_string = "hi there"
print("The string is :")
print(my_string)
print("All possible permutation are :")
calculate_permutations(my_string)

출력

The string is :
hi there
All possible permutation are :
hi there
there hi

설명

  • 필요한 패키지인 itertools.permutations를 환경으로 가져옵니다.

  • 'calculate_permutations'라는 이름의 메서드를 정의하며, 이 메서드는 문자열을 매개변수로 받습니다.

  • 전달받은 문자열은 공백을 기준으로 분리(split)됩니다.

  • 분리된 단어들은 리스트로 변환된 후 변수에 저장됩니다.

  • 생성된 순열을 하나씩 반복하며 각 단어를 콘솔에 출력하고, 한 순열이 끝날 때마다 빈 줄을 출력해 구분합니다.

  • 메서드 외부에서 문자열을 정의한 뒤 콘솔에 출력합니다.

  • 정의된 문자열을 매개변수로 전달하여 메서드를 호출합니다.

  • 최종 결과가 콘솔에 출력됩니다.

핵심 포인트

itertools.permutations는 입력된 요소들의 모든 순서 조합을 튜플 형태로 반환하는 이터레이터입니다. n개의 단어가 있을 때 생성되는 순열의 개수는 n! (팩토리얼)이므로, 단어 수가 많아질수록 결과의 개수가 급격히 증가한다는 점을 유의해야 합니다. 예를 들어 단어가 5개라면 120개의 순열이 생성됩니다.