알고리즘과 친해지기 (2) - 최빈값 찾기

몽슈뜨·2022년 11월 21일
0
post-thumbnail
def find_alphabet_occurrence_array(string):     # 성민섭 백죽 Lv.5
    alphabet_occurrence_array = [0] * 26

    # 이 부분을 채워보세요!
    for num in string:
        if not num.isalpha():
            continue
        asc = ord(num) - ord("a")
        alphabet_occurrence_array[asc] += 1

    max_num = 0
    index = 0

    for i, value in enumerate(alphabet_occurrence_array):
        if value > max_num :
            index = i
            max_num = value
            # print(chr(i + ord('a')))
            # print(value)
            # print(i)
            # print(ord('a'))
            #인덱스(index) 학생 번호  // 첫번째 요소의 값이 머냐. 

    return chr(index + ord('a'))

print(find_alphabet_occurrence_array("hello my name is sparta"))

string에 들어온 인수(argument)를
for문을 사용하여 string의 값이 알파벳인지 검사를 위해
하나씩 값을 가져와 변수 num에 담아줍니다.

num이 알파벳이 맞다면 아스키코드로 변환해줍니다.
변환해준 asc(num)을 알파벳 순서대로 나열하기 위해
알파벳의 시작인 'a'의 아스키 코드 값을 빼줍니다.

알파벳 갯수만큼 빈 배열을 만들어
asc(num) - asc(a)한 값을 넣어줍니다.

알파벳 배열에 num이 들어갈때 마다 +1 씩 해줍니다.
그럼 가장 많이 사용한 알파벳을 알 수 있게 됩니다.

알파벳 배열의 인덱스와 요소를 알아낸 후
최대값을 구해줍니다.

최대값의 인덱스에 asc'a'를 더해줘서 알파벳으로
변환해줍니다.

profile
개발자되면 맥북사줄께

0개의 댓글