오늘의 문제...
Q. 대문자와 소문자가 섞여있는 문자열 s가 주어집니다. s에 'p'의 개수와 'y'의 개수를 비교해 같으면 True, 다르면 False를 return 하는 solution를 완성하세요.
'p', 'y' 모두 하나도 없는 경우는 항상 True를 리턴합니다. 단, 개수를 비교할 때 대문자와 소문자는 구별하지 않습니다.
예를 들어 s가 "pPoooyY"면 true를 return하고 "Pyy"라면 false를 return합니다.
def solution(s):
s = s.lower()
answer = s.count('p') == s.count('y')
return answer
시도한 것
def solution(n):
return s.lower().count('p') == s.lower().count('y')
새롭게 알게 된 것
from collections import Counter
def numPY(s):
c = Counter(s.lower())
return c['y'] == c['p']
새롭게 알게 된 것
Counter 함수는 초면이라서 사용법과 예제를 찾아서 정리해 보았다.
from collections import Counter
# Counter(list) - 배열을 인자로 받는 경우
Counter(['a', 'b', 'c', 'c', 'a', 'd', 'a'])
>>> Counter({'a': 3,'b': 1,'c': 2,'d': 1})
# Counter(문자열) - 문자열을 인자로 받는 경우
Counter("hello world")
>>> Counter({"h": 1, "e": 1, "l": 3, "o": 2, " ": 1, "w": 1, "r": 1, "d": 1}) #공백도 집계 가능
파이썬은 유용한 내장 함수가 정말 많은 것 같다 🫢