문제 13: 애너그램 그룹화

발행: (2026년 2월 10일 오전 11:53 GMT+9)
3 분 소요
원문: Dev.to

Source: Dev.to

개요

주어진 문자열 리스트에서 서로 애너그램인 단어들을 그룹화하는 함수를 작성하는 것이 과제입니다.
애너그램은 다른 단어의 모든 글자를 정확히 한 번씩 사용해 순서를 바꿔 만든 단어나 구절을 말합니다.

예시

group_anagrams(['listen', 'silent', 'hello', 'world', 'enlist'])

예상 출력

[['listen', 'silent', 'enlist'], ['hello'], ['world']]

해결 방법

Python 구현

def group_anagrams(words):
    """
    Groups words that are anagrams of each other.
    """
    # Edge case: None or empty input
    if not words:
        return []

    anagram_groups = {}

    for word in words:
        # Create a case‑insensitive, sorted tuple as the dictionary key
        key = tuple(sorted(word.lower()))

        if key in anagram_groups:
            anagram_groups[key].append(word)
        else:
            anagram_groups[key] = [word]

    return list(anagram_groups.values())

테스트

print(group_anagrams(['listen', 'silent', 'hello', 'world', 'enlist']))
# Output: [['listen', 'silent', 'enlist'], ['hello'], ['world']]

설명

  1. 예외 상황 처리wordsNone이거나 빈 리스트이면 빈 리스트를 반환합니다.
  2. 각 단어에 대한 서명 생성
    • 단어를 소문자로 변환(word.lower())하여 대소문자를 구분하지 않게 합니다.
    • 문자들을 정렬(sorted(...))합니다.
    • 정렬된 리스트를 튜플로 변환해 딕셔너리 키로 사용할 수 있게 합니다.
  3. 단어 그룹화 – 딕셔너리(anagram_groups)를 사용해 각 서명 튜플을 키로, 해당 서명을 공유하는 단어 리스트를 값으로 저장합니다.
  4. 그룹 반환 – 딕셔너리의 값 뷰를 리스트로 변환해 반환합니다.

['listen', 'silent', 'hello'] 로 진행한 단계별 설명

단계단어키 (정렬된 튜플)동작
1listen('e', 'i', 'l', 'n', 's', 't')새 항목 생성 → {'...': ['listen']}
2silent('e', 'i', 'l', 'n', 's', 't')키 존재 → 추가 → {'...': ['listen', 'silent']}
3hello('e', 'h', 'l', 'l', 'o')새 항목 생성 → {'...': ['hello']}

결과: [['listen', 'silent'], ['hello']]

행복한 코딩 되세요! 💻

Back to Blog

관련 글

더 보기 »