알고리즘/이론

[알고리즘] 문자열에서 알파벳 중에 가장 많이 나온 알파벳 찾기/ 최빈값 찾기 python

자바칩 프라푸치노 2021. 6. 12. 17:27

"hello my name is sparta"

이라는 문자열에 어떤 알파벳이 제일 많이 사용되었을까?

 

 

2021.06.12 - [알고리즘/이론] - [알고리즘] 최댓값 찾기 python

input = "hello my name is sparta"

# 문자를 숫자로 변하는 법
#  ord(a)
# 숫자를 문자로 변하는 법
# chr(숫자)
def find_max_occurred_alphabet(string):
    alphabet_occurrence_array = [0] * 26

    for char in string:
        if not char.isalpha():
            continue
        arr_index = ord(char) - ord('a')
        alphabet_occurrence_array[arr_index] += 1

    max_occurrence = 0
    max_alphabet_index = 0
    for index in range(len(alphabet_occurrence_array)):
        # 알파벳별 빈도수
        alphabet_occurrence = alphabet_occurrence_array[index]

        if alphabet_occurrence> max_occurrence:
            max_alphabet_index = index
            max_occurrence = alphabet_occurrence
    print(max_alphabet_index)
    return chr(max_alphabet_index+ ord('a'))

result = find_max_occurred_alphabet(input)
print(result)

 

 

728x90