본문 바로가기
알고리즘/프로그래머스

[Python] 프로그래머스 파일명 정렬

by 컴공맨 2021. 4. 25.
 

코딩테스트 연습 - [3차] 파일명 정렬

파일명 정렬 세 차례의 코딩 테스트와 두 차례의 면접이라는 기나긴 블라인드 공채를 무사히 통과해 카카오에 입사한 무지는 파일 저장소 서버 관리를 맡게 되었다. 저장소 서버에는 프로그램

programmers.co.kr


풀이

cmp_to_key를 사용해 정렬 조건을 만들어 해결했습니다.


코드

from functools import cmp_to_key


def solution(files):
    answer = []

    files_list = list()

    for file in files:
        temp = ""
        flag = False
        file_info = list()

        for idx in range(len(file)):
            temp += file[idx]

            if file[idx].isdigit():
                file_info.append(temp[:-1].lower())
                temp = ""
                flag = True

                for i in range(5):
                    if file[idx].isdigit():
                        temp += file[idx]
                        idx += 1

                        if idx >= len(file):
                            break
                    else:
                        break

                file_info.append(int(temp))

            if flag:
                file_info.append(file)
                files_list.append(file_info)
                break

    files_list = sorted(files_list, key=cmp_to_key(compare))
    answer = [a[2] for a in files_list]

    return answer


def compare(x, y):
    if x[0] > y[0]:
        return 1
    elif x[0] < y[0]:
        return -1
    else:
        if x[1] > y[1]:
            return 1
        elif x[1] < y[1]:
            return -1
        else:
            return 0

 

pyo7410/Algorithm

1일 1커밋을 목표로! Contribute to pyo7410/Algorithm development by creating an account on GitHub.

github.com