[백준] 1157 파이썬 (단어 공부)

노을·2022년 3월 17일
0

Algorithm

목록 보기
14/21
post-thumbnail

코드

1. 나의 코드


alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
words = input().upper()

list = []
for i in alphabet:
    count = 0
    for j in words:
        if i==j:
            count += 1
    list.append(count)

if list.count(max(list)) > 1:
    print('?')
    
else:
    index = list.index(max(list))
    print(alphabet[index])
        

<풀이>

alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
words = input().upper()

먼저 알파벳 대문자를 alphabet에 넣어준다.
대문자를 출력할 것이기 때문에 words를 upper()를 이용해 대문자로 바꿔준다.

a부터 z까지의 경우를 for문을 돌린다.
count는 0으로 초기화 해주었다.
해당하는 알파벳이 words에 있을 경우 count를 +1 해준다.
count를 list에 넣는다.

list의 최댓값이 2개 이상인 경우, '?'를 출력한다.
list의 최댓값이 1개인 경우, list의 최댓값 인덱스를 구하여 가장 많이 사용된 알파벳을 출력한다.


2. 남의 코드 (set 이용)

words = input().upper()
unique_words = list(set(words))
count_list = []

for i in unique_words:
    count = words.count(i)
    count_list.append(count)

if count_list.count(max(count_list)) > 1:
    print('?')
else:
    index = count_list.index(max(count_list))
    print(unique_words[index])



<풀이>

입력받은 words를 upper()를 이용해 대문자로 바꿔준다.

unique_words = list(set(words))

set()으로 중복을 없애 unique_words에 넣어준다.

for i in unique_words:
    count = words.count(i)
    count_list.append(count)

unique_words에 있는 알파벳의 인덱스를 구해 count_list에 넣는다.

if count_list.count(max(count_list)) > 1:
    print('?')
    

가장 많이 사용된 알파벳의 개수가 2 이상이면 '?'출력

else:
    index = count_list.index(max(count_list))
    print(unique_words[index])

1개인 경우, count_list 최댓값의 인덱스를 구하여
가장 많이 사용된 알파벳을 출력한다.

0개의 댓글