[BOJ] 1302 베스트셀러

[BOJ] 1302 베스트셀러

문제 링크

이 문제는 조금 시간이 걸렸찌만 두 쌍의 값이 있어야한다는 것을 인지하고 dictionary? map?을 사용해야한다는 것을 알았다.

그래서 다음과 같이 풀이했다.

나의 풀이

N = int(input())

m = {}
temp = 0
result = ""

for _  in range(0, N):
    sold_item = input()

    if(sold_item in m):
        m[sold_item] += 1
    else:
        m[sold_item] = 1

for k in m:
    if(temp < m[k]):
        temp = m[k]
        result = k
    elif (temp == m[k]):
        if(result[0:1] > k[0:1]):
            result = k
    else:
        continue


print(result)

이렇게 풀이했을 때 내 개발환경에서는 테스트 케이스를 모두 넣어봤을 때 틀린 값이 없었는데, 백준에서 Python3로 세팅하고 정답을 제출하니 틀렸다고 한다.

Python의 함수들을 잘 모르는 탓에 어영부영 구현하긴 했어도.. 값은 맞는데 ㅜㅜ 시간 초과도 아니고.. 왜 값이 틀리지?

해설을 보고 깨달음

  • m={} 말고 m = dict()로 선언해도 된다.
  • 크기 비교하는 로직은 굳이 구현할 필요 없이 max()함수를 이용하면 된다.
  • Dictionary 순회
dictionary = {
  "a" : "a",
  "b" : "b",
}

for m in dictionary.items(): #키, 값
  print(m) # ('A', a) ('B', 'b')

for m in dictionary: #키
  print(m) # A B  

for m in dictionary.values(): #값
  print(m) # a b  

  • dictionary.items() = 키, 값 모두
  • dictionary = 키만
  • dictionary.values() = 값만

강사님 풀이


d = dict()
for _ in range(int(input())):
  book = input()
  if book in d:
    d[book] += 1
  else:
    d[book] = 1

m = max(d.values())
candi = []
for k, v in d.items():
  if v== m:
    candi.append(k)

candi.sort()
print(candi[0])


© 2021. All rights reserved.