sorted()와 collections.Counter() 함수를 사용하여 문자열 아나그램 판별 (문자 재배열 가능 여부)

HEE·2025년 4월 16일
0
post-thumbnail

아나그램 이란?

  • 두 문자열이 동일한 문자들로만 구성되어 있고,
  • 순서만 다른 경우.

1. 프로그래머스 python 코딩테스트 입문

Level 0. A로 B 만들기

문자열 before와 after가 매개변수로 주어질 때, before의 순서를 바꾸어 after를 만들 수 있으면 1을, 만들 수 없으면 0을 return 하도록 solution 함수를 완성해보세요.

정답 확인

1. 간단하고 직관적 sorted()

def solution(before, after):
    return 1 if sorted(before) == sorted(after) else 0

2. 정확하고 빠르게 collections.Counter()

from collections import Counter
def solution(before, after):
    return 1 if Counter(before) == Counter(after) else 0

핵심 체크

  1. 문제의 핵심은 두 문자열이 같은 글자 + 같은 글자 개수를 갖는지 확인해야함.
  2. sorted()로 단순하게 풀수도 있으나, collections.Counter 함수 배워보기.

collections.Counter 함수 정리.

문자나 요소의 개수를 자동으로 세서 딕셔너리 형태로 저장해주는 파이썬 클래스.

예시

from collections import Counter
before = "apple"
after = "ppale"
Counter(before)  # 결과: Counter({'p': 2, 'a': 1, 'l': 1, 'e': 1})
Counter(after)   # 결과: Counter({'p': 2, 'a': 1, 'l': 1, 'e': 1})
Counter(before) == Counter(after)  # ✅ True
  • 문자열에서 문자 개수 세기
  • 리스트에서 중복 요소 개수 세기
  • 데이터 전처리시 빈도 분석
  • 아나그램문제, 투표결과 집계, 가장 많이 나온 항목찾기 등

profile
ALL IS WELL

0개의 댓글