아나그램
이란?
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
핵심 체크
- 문제의 핵심은 두 문자열이 같은 글자 + 같은 글자 개수를 갖는지 확인해야함.
- 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