본문 바로가기
알고리즘 & PS

[프로그래머스] Lv2 - 튜플

by 다람이도토리 2021. 10. 8.

* 간만에 코딩테스트를 볼 일이 생겨서, 문제 풀이를 다시 연습해보았다.

https://programmers.co.kr/learn/courses/30/lessons/64065

풀이법은 간단하다. 주어진 집합은 문자열로 한글자씩 들어오므로 숫자만 찾아준다.
수들이 몇개 있는지 세준다.

먼저 들어온 수부터 정렬을 해주면 깔끔하게 원하는 튜플을 얻게 된다.
다시 말해 맨 처음 들어 온 수가 가장 많은 개수만큼 들어올 것이니까.

import string
def solution(s):
    tuple = {}
    i = 0
    while i < len(s):
        if s[i].isnumeric():
            start = i
            end = start + 1
            while s[end].isnumeric():
                end += 1
            cut = s[start:end]
            if cut in tuple:
                tuple[cut] += 1
            else:
                tuple[cut] = 1
            i = end
        else:
            i += 1
    # sort tuple by key
    tuple = sorted(tuple.items(), key = lambda x : x[1], reverse = True)
    return [int(i[0]) for i in tuple]