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

2022. 8. 15. 21:55알고리즘/프로그래머스

반응형

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

파일명 정렬

2018 KAKAO BLIND RECRUITMENT

문제

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

풀이

isdigit()을 통해서 Head, Number, TAIL 파트를 구별하였고 분리해서 배열로 넣어 lambda를 통한 정렬을 진행했습니다.

파일명을 받아서 분리를 진행합니다.

img12.png 의 경우 ["img12.png","img",12,".png"] 가 되도록 만들었습니다.

분리가 된 배열들을 lambda를 통해서 정렬을 진행합니다.

주의해야할 점은 가운데 Number 파트가 최대 연속된 5글자라는 점입니다.

풀이코드


def solution(files):
    answer = []
    files_list = []
    for file in files:
        count = 0
        length = len(file)
        file_list =[]
        file_list.append(file)
        tmp = []
        while(not file[count].isdigit() and count<length): #HEAD
            tmp.append(file[count])
            count+=1
        file_list.append(''.join(tmp).lower())
        tmp =[]
        number = 0
        while(count<length and file[count].isdigit() and number <5):  #Number
            tmp.append(file[count]) 
            count+=1
            number+=1
        file_list.append(int(''.join(tmp)))
        tmp =[]
        while(count<length): #TAIL
            tmp.append(file[count])  
            count+=1
        file_list.append(''.join(tmp).lower())
        files_list.append(file_list)
    files_list.sort(key = lambda x: (x[1], x[2]))
    # print(files_list)
    for file_list in files_list:
        answer.append(file_list[0])
    return answer

가장 인기 많은 코드


import re

def solution(files):
    a = sorted(files, key=lambda file : int(re.findall('\d+', file)[0]))
    b = sorted(a, key=lambda file : re.split('\d+', file.lower())[0])
    return b

반응형