프로그래머스. 파일명 정렬 파이썬 풀이

minan·2021년 6월 29일
0

프로그래머스

목록 보기
78/92

프로그래머스. Level 2. 파일명 정렬 파이썬 풀이

문제링크 https://programmers.co.kr/learn/courses/30/lessons/17686#

정규식을 이용하면 간결하게 해결가능하지만 잘모르기 때문에 반복문으로 해결하였음

def solution(files):
    answer = []

    temp = []
    index = -1
    for file in files:
        # 대소문자를 구분하지 않으니 소문자로 변경
        file = file.lower()
        # 원래 파일 순서
        index += 1
        # HEAD
        name = "" 
        # NUMBER
        num = ""
        # TAIL
        tail = ""
        
        # HEAD 구하기
        for i in range(len(file)):
            if file[i].isdigit():
                file = file[i:]
                break
            else:
                name += file[i]
        
        # NUMBER 구하기
        for i in range(len(file)):
            if not file[i].isdigit():
                file = file[i:]
                break
            else:
                num += file[i]
        
        # 나머지는 TAIL
        tail = file
        
        # [head, number, tail, index] 배열에 추가
        temp.append([name, num, tail, index])
            
            
    # Head, num, index순으로 정렬
    temp = sorted(temp, key=lambda x: (x[0], int(x[1]), x[3]))

    # index를 이용하여 원래 이름 결과 배열에 추가
    for file in temp:
        answer.append(files[file[3]])

    return answer
profile
https://github.com/minhaaan

0개의 댓글