본문 바로가기
Problem Solving

[Hash Table] 과일가게: 가장 많이 팔린 과일

by Bokoo14 2022. 12. 13.
N개의 과일 판매 목록이 주어졌을 때, 가장 많이 팔린 과일을 출력하시오.
만일, 가장 많이 팔린 과일이 여러 개 있으면, 알파벳 순서가 가장 빠른 과일을 출력하시오.
Input
첫째 줄에 과일 판매 목록의 길이 N이 주어진다.
둘째 줄부터 N개의 줄에 한 줄에 하나씩 판매한 과일의 이름이 주어진다.
37
orange
blueberry
strawberry
strawberry
strawberry
strawberry
orange
blueberry
pear
lemon
lemon
orange
tomato
apple
blueberry
kiwi
orange
blueberry
kiwi
pear
melon
lemon
orange
orange
tomato
strawberry
apple
pear
strawberry
strawberry
melon
banana
orange
blueberry
pear
melon
tomato

Output
첫째 줄에 과일 판매 목록에서 가장 많이 팔린 과일의 이름을 출력한다.
만일, 가장 많이 팔린 과일이 여러 개 있으면, 알파벳 순서가 가장 빠른 과일을 출력한다.
둘째 줄에 가장 많이 팔린 과일이 몇 번 팔렸는지 출력한다.
orange
7
import sys
input = sys.stdin.readline

n = int(input())
fruit = [input().strip() for _ in range(n)] # 과일들 입력받기

sale = {} # 해시테이블 생성
def sol(fruit, n):
    for i in fruit:
        if i in sale: # 해시테이블에 이미 있다면 개수만 증가
            sale[i]+=1 
        else: # 해시테이블에 없는 새로운 과일이라면 추가
            sale[i]=1

sol(fruit, n)
answer = sorted(sale.items(), key = lambda x: (-x[1], [x[0]]) )# 해시 테이블 정렬. 가장 많이 팔린 과일이 여러 개 있으면, 알파벳 순서가 가장 빠른 과일 우선
print(answer[0][0]) # 가장 많이 팔린 과일 이름
print(answer[0][1]) # 가장 많이 팔린 과일 횟수

'Problem Solving' 카테고리의 다른 글

[Hash Table] 로마숫자의 소인수  (0) 2022.12.13
[Hash Table] 과일 가게: 많이 팔린 순서로 정렬  (0) 2022.12.13
[Queue] 카드 버리기  (0) 2022.12.13
[Stack] 내림차순 수열  (0) 2022.12.13
[Stack] 괄호의 완성  (0) 2022.12.13