본문 바로가기

개발/algorithm

[프로그래머스][level2] [3차] 파일명 정렬 - python

문제 링크

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

 

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

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

programmers.co.kr

 

풀이

모든 파일명에 대하여 반복문으로

숫자 등장 전까지 head, 숫자 등장 후 문자 등장 전까지 num, 문자 등장부터 마지막까지 tail 구하고,

data에 대입해준 후 head, num 순으로 정렬해주었다. 이 때 head는 소문자로 통일하고 num은 int 로 변환해주어야 한다. 

def solution(files):
    answer = []
    data = []
    for f in files :
 
        head, num, tail = '', '', ''
        index = len(f)-1
        
        # 숫자 등장 인덱스 구하기 
        for i in range(len(f)):
            if f[i].isdigit():
                index = i 
                break
                
        # 숫자 등장 전까지 head
        head = f[:index]
        num = f[index:]
        
        for i in range(len(num)):
        	# 문자 등장 인덱스 구하기 
            if not num[i].isdigit():
                tail = num[i:]
                num = num[:i]
                break
        
        data.append((head, num, tail))
        
    # 파일명, 번호 순으로 정렬 -> 소문자로 통일해야함 
    data.sort(key = lambda x : (x[0].lower(), int(x[1])))
    
    for i in data:
        answer.append("".join(i))
    return answer

 다른 사람들의 풀이를 보니 정규 표현식으로 코드를 매우 간결하게 짤 수 있었다. 

import re 

def solution(files):
    # file의 숫자를 기준으로 split
    answer = [re.split(r"([0-9]+)", f) for f in files ]
    answer.sort(key = lambda x : (x[0].lower(), int(x[1])))
    
    return [ "".join(i) for i in answer]