BOJ/🥈

★Set/Map Upper-Intermediate I - 3 Solved★

metamong 2023. 8. 11.

★ 2910 빈도 정렬 ★

 

import sys
input=sys.stdin.readline

N,C=map(int,input().split())
freq=dict()

message=list(map(int,input().split()))

order=1
for n in message:
    if n not in freq:
        freq[n] = [1, order]
        order += 1
    else:
        freq[n][0] += 1

freq_sorted = sorted(freq.items(), key=lambda x:(-x[1][0],x[1][1]))

for x in freq_sorted:
    for _ in range(x[1][0]):
        print(str(x[0]),end=' ')

 

🧑🏻‍🎨 hash table의 key값은 고유한 숫자, value는 숫자의 빈도와 숫자 출현 순서 두 개를 list 형태로 저장하게끔 구성할 수 있다

 

🧑🏻‍🎨 알아야 할 것 ①

아래 예시 확인: 먼저 빈도수 기준에 맞게 정렬(default 오름차순이므로 앞에 - 붙여 내림차순 / order 오름차순이므로 그대로)

※ dictionary sorted() lambda function 사용 code 꼭 익숙해지기

🧑🏻‍🎨 알아야 할 것 ②

: 메모리 절약을 위해 애초에 dictionary를 모든 자연수로 초기화하지 말고, 등장하는 부분만 key를 만든다


★ 20920 영단어 암기는 괴로워 ★

import sys
input=sys.stdin.readline
from collections import defaultdict

N,M=map(int,input().split())
note=defaultdict(list)
for _ in range(N):
    word=input().rstrip()
    if len(word)>=M:
        if word in note.keys():
            note[word][0]+=1
        else:
            note[word].extend([1,len(word)])
note=sorted(note.keys(),key= lambda x: (-note[x][0],-note[x][1],x))
print(*note,sep='\n')

 

🧑🏻‍🎨 dictionary sorting

: defauldict로 list가 key인 dictionary를 만들어 [빈도수, 길이] update. key = lambda x: 로 list의 첫번째 요소 먼저 → list의 두번째 요소 → key 값 alphabetical order 정렬 code (lambda x : (-note[x][0], -note[x][1], x)) 거꾸로 정렬하고 싶다면 숫자의 경우 앞에 마이너스 부호(-) 붙이기


★ 15237 Cipher ★

import sys
input=sys.stdin.readline
from collections import defaultdict

N,C=map(int,input().split())
message = list(map(int,input().split()))
freq = dict()
for i in range(N):
    if message[i] in freq.keys():
        freq[message[i]][0] += 1
    else:
        freq[message[i]] = [1,i]
freq = sorted(freq.items(),key=lambda x:(-x[1][0],x[1][1]))
ans=[]
for x in freq:
    ans.extend([str(x[0])]*(x[1][0]))
print(*ans)

 

🧑🏻‍🎨 dictionary의 value를 list로 설정. list의 첫번째 value는 frequency, 두번째 value는 첫 등장하는 index

: frequency 순 정렬 뒤, 첫 등장하는 index 순 정렬. dictionary 정렬 시 freq.items() 인자로 쓰고, x[0]이 아닌 x[1][0], x[1][1] 사용


 

 

 

 

 

 

 

 

 

 

 

 

댓글