반응형
https://school.programmers.co.kr/learn/courses/30/lessons/42578?language=python3
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
내 코드
코드 리뷰
해시
from collections import defaultdict
def solution(clothes):
answer = 1
type = dict()
for item, category in clothes:
if category in type:
type[category].append(item)
else:
type[category] = item
print(type)
return answer
틀린 코드, 처음에는 이 코드로 기본 세팅을 했는데 틀렸다. 자꾸만 'str' object has no attribute 'append' 이 오류가 발생했다. 이유가 대체 뭘까 하고 보니 실제로 문자열은 append를 사용할 수 없다. 하지만 type[category]에 대해 초기에 문자열로 초기화가 되어 있던 것이다. 그래서 오류가 발생했다.
type = defaultdict(list)
for item, category in clothes:
type[category].append(item)
print(type)
그래서 이를 고려하여 다음과 같이 수정했다. default값을 list로 함으로써, str를 넣더라도 리스트로 인식하여 append를 사용할 수 있도록 했더니 오류가 나지 않았다!
반응형
'코딩테스트 대비 > 프로그래머스' 카테고리의 다른 글
| [Python][프로그래머스] lv3. 섬 연결하기 (1) | 2023.10.06 |
|---|---|
| [Python][프로그래머스] lv3. 디스크 컨트롤러 (0) | 2023.10.05 |
| [Python][프로그래머스] lv3. 베스트앨범 (2) | 2023.10.05 |
| [Python][프로그래머스] lv3. 보석 쇼핑 (0) | 2023.09.27 |
| [Python][프로그래머스] lv2. 전화번호 목록 (0) | 2023.07.10 |