https://school.programmers.co.kr/learn/courses/30/lessons/132265
나의 풀이 ( 시간 초과 )
슬라이싱을 이용해 비교하니 시간 초과되었다.
def solution(topping):
count=0
for i in range(1, len(topping)):
if len(set(topping[:i])) == len(set(topping[i:])):
count+=1
return count
모범 답안
from collections import Counter
def solution(topping):
answer = 0
old = Counter(topping)
young = set()
for i in topping:
old[i] -= 1
young.add(i)
if old[i] == 0:
old.pop(i)
if len(old) == len(young):
answer +=1
return answer
학습한 것
Counter는 여러 형태의 데이터를 인자로 받아 중복된 데이터가 저장된 배열을 인자로 넘기면 각 원소가 몇 번씩 나오는지 저장된 객체를 얻을 수 있다.
>>> Counter(["hi", "hey", "hi", "hi", "hello", "hey"])
Counter({'hi': 3, 'hey': 2, 'hello': 1})
참조
https://www.daleseo.com/python-collections-counter/
파이썬 collections 모듈의 Counter 사용법
Engineering Blog by Dale Seo
www.daleseo.com
'코딩테스트 > programmers (python)' 카테고리의 다른 글
Programmers / 2단계 / 택배상자 / python (0) | 2024.03.22 |
---|---|
Programmers / 2단계 / 숫자 변환하기 / python (0) | 2024.03.22 |
Programmers / 3단계 / 이중우선순위큐 / python / heapq (0) | 2024.03.18 |
다익스트라(dijkstra) 알고리즘 파이썬 구현 코드 (1) | 2024.03.18 |
Programmers / 3단계 / 단어 변환 / python / DFS/BFS (0) | 2024.03.16 |