관리 메뉴

솜씨좋은장씨

[BaekJoon] 25859번 : Sort by Frequency (Python) 본문

Programming/코딩 1일 1문제

[BaekJoon] 25859번 : Sort by Frequency (Python)

솜씨좋은장씨 2022. 11. 22. 12:00
728x90
반응형

코딩 1일 1문제! 오늘의 문제는 백준의 Sort by Frequency 입니다.

 

25859번: Sort by Frequency

The input consists of a single string, appearing on a line by itself, starting in column 1 and not exceeding column 70. The input will contain only lowercase letters (at least one letter).

www.acmicpc.net

🧑🏻‍💻 문제 풀이

입력 받은 단어를 collections 의 Counter 를 활용하여 단어 속에 있는 알파벳을 카운팅 한 다음

카운팅 된 수 내림차순 -> 알파벳 오름차순으로 정렬한 뒤

cnt_items = sorted(Counter(word).items(), key=lambda x: (-x[1], x[0]))

해당 값으로 정답을 만들었습니다.

answer = ""

for item in cnt_items:
    answer += item[0] * item[1]

전체 코드는 아래를 참고해주세요.

🧑🏻‍💻 코드 ( Solution )

from collections import Counter


def sort_by_frequency(word):
    answer = ""
    cnt_items = sorted(Counter(word).items(), key=lambda x: (-x[1], x[0]))
    
    for item in cnt_items:
        answer += item[0] * item[1]
        
    return answer


if __name__ == "__main__":
    word = input()
    print(sort_by_frequency(word=word))
 

GitHub - SOMJANG/CODINGTEST_PRACTICE: 1일 1문제 since 2020.02.07

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments