⭐ 문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/132265
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
⭐ 풀이 코드
❌ 시간초과
def solution(topping):
answer = 0
for i in range(len(topping)):
a = set(topping[:i])
b = set(topping[i:])
if len(a) == len(b):
answer += 1
return answer
리스트 슬라이싱을 사용했더니 시간초과가 발생했다!..
⭕ 통과
from collections import Counter
def solution(topping):
answer = 0
topping_c = Counter(topping) # topping 원소 개수
topping_s = set() # topping 개수 비교를 위한 새로운 집합
for t in topping:
topping_s.add(t)
topping_c[t] -= 1
if topping_c[t] == 0:
topping_c.pop(t)
if len(topping_c) == len(topping_s):
answer += 1
return answer
다른 사람 풀이 참고해서 Counter를 사용했다.
- topping_c와 topping_s를 정의
- topping 원소를 반복하면서 topping_s에 원소 추가, topping_c의 원소 value값 1씩 빼주기
- topping_c에 더 이상 원소가 없을 경우, 원소 제거
- topping_c와 topping_s의 원소 개수가 같을 경우, 카운트
'Python > Programmers' 카테고리의 다른 글
[프로그래머스/Python] Lv 2. 주식가격 (0) | 2023.05.01 |
---|---|
[프로그래머스/Python] Lv 2. 숫자 변환하기 (0) | 2023.04.23 |
[프로그래머스/Python] Lv 1. 바탕화면 정리 (0) | 2023.04.23 |
[프로그래머스/Python] Lv 2. 큰 수 만들기 (0) | 2023.04.23 |
[프로그래머스/Python] Lv1. 성격 유형 검사하기 (0) | 2023.04.21 |