https://www.acmicpc.net/problem/1181
난이도: 실버5
▶ 문제 탐색하기
N : 단어의 개수 (1 ≤ N ≤ 20,000)
word : 단어들 (알파벳 소문자, len(word) ≤ 50)
◇ 원하는 출력 조건
- len(word) 증가하는 순(=오름차순)으로 출력
- len(word)가 같다면 알파벳 사전 순으로 출력
▶ 코드 설계하기
len(word)들의 오름차순 정렬들이 진행됨과 동시에 동일한 len에 대해서는 str의 사전 순으로 정렬되어야한다.
dictionary = dict(zip(arr, length))
# {'but': 3, 'cannot': 6, 'hesitate': 8, 'i': 1, 'im': 2, 'it': 2, 'more': 4, 'no': 2, 'wait': 4, 'wont': 4, 'yours': 5}
위와 같이 중복을 없애주고 사전식으로 정렬한다.
sorted_keys = sorted(data.items(), key=lambda item: item[1])
items() 함수를 사용해 키-값 쌍을 가져오고, lambda 함수로 값을 기준으로 정렬한다.
▶ 회차별 수정사항
- arr = [but, i, wont, hesitate, no, more, no, more, it, cannot]에서 'no'나 'more'과 같이 중복되는 단어를 제외하고 정렬하고 싶다면 배열을 집합으로 변환하여 중복을 제거해야한 후, 다시 집합을 배열로 변환하여 정렬한다.
ex) arr = sorted(set(arr)) - for문으로 len을 우선 정렬한 후, if 문을 써서 동일 len에 대해 사전 정렬하려 했으나 머리가 아파서 포기.
- 단어들의 배열인 arr과 단어 길이에 대한 배열인 length를 일대일 대응되도록 {key: value}로 만들었다.
ex) 두 길이가 같은 배열을 딕셔너리로 결하는 법: dict( zip( arr1, arr2 ))
▶ 정답 코드
N = int(input()) # 1~20000
arr = [] # 0 1 2 3 4 5 6..key로 두고
length = [] # 3 1 4 7 value로 두자
for i in range(N):
word = str(input()) # but, i, wont, hesitate
arr.append(word) # arr = [but, i, wont, hesitate, no, more, no, more, it, cannot]
arr = sorted(set(arr)) # ['but', 'cannot', 'hesitate', 'i', 'im', 'ir', 'more', 'more', 'no', 'no', 'wait', 'wont', 'yours']
length =[]
for j in arr:
length.append(len(j))
dictionary = dict(zip(arr, length))
sorted_keys = sorted(dictionary.items(), key=lambda item: item[1])
for key in sorted_keys:
print(key[0])
▶ 추가 풀이
https://sponge-nitrogen-136.notion.site/fe88578fb8224d1798ac70bf4a4d0404
생일 | Notion
📌 문제 탐색하기
sponge-nitrogen-136.notion.site
'코딩테스트 > BOJ' 카테고리의 다른 글
[백준] 2578번: 빙고 (0) | 2024.07.01 |
---|---|
[백준] 25305번: 커트라인 (0) | 2024.06.28 |
[백준] 5635번: 생일 (0) | 2024.06.27 |
[백준] 10814번: 나이순 정렬 (0) | 2024.06.25 |
[백준] 2309번: 일곱 난쟁이 (0) | 2024.06.24 |