Python/online judge

백준 [1157.단어 공부] | Python

구름솜:D 2023. 11. 17. 17:01
728x90

✏️ 문제

https://www.acmicpc.net/problem/1157

 

1157번: 단어 공부

알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.

www.acmicpc.net

 

✏️ 풀이방법

1. 대문자로 출력하기 때문에 모든 알파벳을 대문자로 변경한 str1리스트

2. 중복을 제외하고 어떤 알파벳이 있는지를 담는 str2리스트

3. str과 str2를 비교해서 동일한 알파벳의 개수 count하는 str_cnt리스트

4. str_cnt에 같은 숫자가 2개 이상이면 가장 많이 사용된 알파벳이 여러개이기 때문에 !출력 아닌경우 max값 출력

 

 

📌 코드

str = list(input().upper())  #모든 알파벳을 대문자로 변경
str2 = list(set(str))  #알파벳의 중복을 제거

str_cnt=[] #알파벳의 개수를 count하는 리스트

for i in range(len(str2)):
    cnt = 0
    for j in range(len(str)):
        if str2[i] == str[j]: 
            cnt+=1
    str_cnt.append(cnt)

if str_cnt.count(max(str_cnt)) >=2:
    print('?')
else:
    print(str2[str_cnt.index(max(str_cnt))])
str = list(input().upper())  #모든 알파벳을 대문자로 변경
str2 = list(dict.fromkeys(str))  #알파벳의 중복을 제거

str_cnt=[] #알파벳의 개수를 count하는 리스트

for i in range(len(str2)):
    cnt = 0
    for j in range(len(str)):
        if str2[i] == str[j]:
            cnt+=1
    str_cnt.append(cnt)

if str_cnt.count(max(str_cnt)) >=2:
    print('?')
else:
    print(str2[str_cnt.index(max(str_cnt))])

 

📌 결과

Mississipi  #입력
?           #출력
zZa  #입력
Z    #출력
baaa  #입력
A     #출력

 

 

🤔 시행착오.1

for i in range(len(str_cnt)):
    for j in range(len(str_cnt)):
        if str_cnt[i] in str_cnt[j]: 
            print('?')
            break
        if str_cnt[i] not in str_cnt:
            print('!')
            break

- i+j할 경우 index out of range 에러발생

 

 

 

🔎 다른풀이

word = input().upper()
word_list = list(set(word))
lst = []

for i in word_list:
    count = word.count(i)
    lst.append(count)

if lst.count(max(lst))>= 2:
    print("?")
else:
    print(word_list[lst.index(max(lst))])

 

 

 

📒 다시보기

 

[Python] 16. 리스트 중복 제거

리스트 내의 중복되는 원소가 있으면 다음과 같은 방법으로 중복을 제거할 수 있다. 1. for문을 사용해서 중복 제거하기 2. set을 사용해서 중복 제거하기 3. dictionary를 사용해서 중복 제거하기 1. fo

somin0416.tistory.com