한 걸음씩

[백준][python] 1181 단어정렬 본문

BOJ

[백준][python] 1181 단어정렬

winter17 2023. 1. 27. 22:31

 

https://www.acmicpc.net/problem/1181

 

1181번: 단어 정렬

첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.

www.acmicpc.net

풀이 과정

1. 입력받은 문자를 voca 변수 리스트에 append

2. set으로 중복제거해 주고 list로 변환해 준다 (왜? set은 sort속성을 갖지 못하기 때문)

3. 알파벳 순서대로 오름차순 정렬 sort()

4. 단어 길이를 기준으로 오름차순 정렬 sort(key=lambda x:len(x))

5. 반복문을 통해서 하나씩 출력

voca = []
N = int(input())  # 13
for n in range(N):
    # 입력을 받아서 리스트로 만든다
    w = input()
    voca.append(w)
# 중복제거
word = list(set(voca))
# sort: 원본 변경, sorted: 사본 생성
# 오름차순 정렬(알파벳 순서대로)
word.sort()

# 단어 길이를 기준으로 오름차순 정렬
word.sort(key=lambda x: len(x))


for i in word:
    print(i)

리뷰

'단어 길이를 기준으로 오름차순 정렬'부분에서 리스트 삽입, 정렬을 통해 코드를 짤 수 있겠지만 더 효율적인 방법이 있는지 구글링 하다가 

발견한 '배열 이진 분할 알고리즘'이란걸 알게 됐다. 

https://docs.python.org/ko/3/library/bisect.html?highlight=sort%20key%20lambda 

 

bisect — Array bisection algorithm

Source code: Lib/bisect.py This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive compariso...

docs.python.org

 

'BOJ' 카테고리의 다른 글

[백준][python] 1927 최소 힙 ✅  (0) 2023.01.27
[백준][python] 20001 고무오리 디버깅  (0) 2023.01.27
[백준][python] 1269 대칭 차집합  (0) 2023.01.27
[백준][python] 2161 카드1 ✅  (0) 2023.01.27
[백준][python] 10773 제로  (0) 2023.01.26