alpyrithm_알파이리즘

[알고리즘][Python] 백준(BOJ) 1181 단어 정렬_파이썬 본문

Algorithm/백준 알고리즘_Python

[알고리즘][Python] 백준(BOJ) 1181 단어 정렬_파이썬

알파이 2020. 2. 11. 19:11

1-3. 탐색과 정렬(2)

B - 1181 단어 정렬    https://www.acmicpc.net/problem/1181

 

1181번: 단어 정렬

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

www.acmicpc.net

 

 

 

 

 

 

문제 풀기 전 공부할 것 : 정렬, set

 

 

 

 

 

 

 

풀이 1

  • 같은 단어가 여러 번 입력된 경우에는 한 번만 출력한다 --> set() 이용
  • 정렬할 때 길이가 짧은 것부터, 길이가 같으면 사전 순 --> sorted()로 사전 순으로 정렬 후 길이가 짧은 것부터 출력한다

==> 정답이긴 하나 시간이 오래 걸리고 난잡한 느낌이 있다.

def sort_short(l, l_len):    # 길이 순으로 정렬
    while l:
        m_idx = l_len.index(min(l_len))
        print(l.pop(m_idx))
        l_len.pop(m_idx)
        
N = int(input())
words = set()
for _ in range(N):
    words.add(input())
    
w = sorted(words)     # 사전 순으로 정렬
w_len = []
for i in w:
    w_len.append(len(i))
    
sort_short(w, w_len)

 

+) 더 간략한 방법을 찾아본다 <= 사전 순, 길이 순의 우선순위를 정하고 한 번에 정렬하는 방법

 

 

풀이 2

  • sort()와 sorted()의 매개 변수인 key를 잘 활용해야 한다.
N = int(input())
words = set()
for _ in range(N):
    word = input()
    words.add((word, len(word)))
    
w = sorted(words, key = lambda x:(x[1], x[0]))  # 길이 순으로 정렬하고 사전 순으로 정렬

for i in w:
    print(i[0])

 

 

풀이 3

  • 딕셔너리(dictionary) 이용한 풀이
words = {}
res = []
N = int(input())
for _ in range(N):
    word = input()
    if len(word) not in words:
        words[len(word)] = [word]
    else:
        if word not in words[len(word)]:
            words[len(word)].append(word)
    
for i in sorted(words.keys()):
    res += sorted(words[i])
    
for j in res:
    print(j)

 

 

 

 

 

 

 

복습

  • sort()
  • sorted()
  • lambda

 

 

 

 

반응형
Comments