Python
[백준] 1302번 : 베스트셀러 ☆
Leunco
2022. 1. 3. 22:59
유형 : 탐색
[예제]
5
top
top
top
top
kimtop
[출력]
top
1. 내 풀이
import sys
N = int(sys.stdin.readline())
_list = []
for _ in range(N):
book = sys.stdin.readline().strip()
_list.append(book)
_list = sorted(_list)
_set = set(_list)
_list2 = list(_set)
_list2 = sorted(_list2)
max = 0
max_book = 0
for i in range(len(_list2)):
cnt = _list.count(_list2[i])
if cnt > max:
max = cnt
max_book = _list2[i]
print(max_book)
▷ sys.stdin.readline()을 사용할 때 개행문자를 자동으로 없애기 위해 뒤에 strip()을 붙였다. (참고)
▷ 책 제목을 입력받은 리스트를 집합 자료형으로 변환시켜(set) 중복인 책을 없애주었다. 그 뒤, 책이 얼마나 입력되었는지 count()로 개수를 셀 수 있었다.
▷ 가장 많이 입력된 책만 출력하면 되므로, 변수 max를 이용해 최대값과 그에 맞는 책제목을 따로 뽑았다.
2. 다른 풀이
출처 : 패스트캠퍼스 - 알고리즘 / 기술면접 완전 정복 올인원 패키지 Online
** 핵심 아이디어
1. 가장 많이 등장한 문자열을 출력하는 문제와 동일하다.
2. 등장 횟수를 계산할 때는 파이썬의 Dictionary 자료형을 이용하면 효과적이다.
n = int(input())
books = []
for _ in range(n):
book = input()
if book not in books:
books[book] = 1
else:
books[book] += 1
target = max(books.values())
array = []
for book, number in books.items():
if number == target:
array.append(book)
print(sorted(array)[0])
문제 출처 : https://www.acmicpc.net/problem/1302
1302번: 베스트셀러
첫째 줄에 오늘 하루 동안 팔린 책의 개수 N이 주어진다. 이 값은 1,000보다 작거나 같은 자연수이다. 둘째부터 N개의 줄에 책의 제목이 입력으로 들어온다. 책의 제목의 길이는 50보다 작거나 같고
www.acmicpc.net
반응형