티스토리 뷰

연습

프로그래머스 파일명 정렬

onaeonae1 2024. 6. 17. 18:06

문자열에 대한 정렬 조건이 주어질 때 그에 대한 정렬을 야무지게 해주면 되는 문제이다

functools 의 cmp_to_key를 적극적으로 사용하면 된다

 

또한 문자열의 조건이 꽤 빡빡하므로 그에 대해 확인하면 된다

-> HEAD, NUMBER, TAIL

이때 HEAD에 공백이 포함될 수 있기 때문에 주의 필요 (테케 6,7,8,9 통과 안되는 이유)

 

from functools import cmp_to_key

def parse(file:str):
    flag = False
    num_sti = -1
    num_edi = -1
    
    for idx, item in enumerate(file):
        if item.isdigit():
            if not flag:
                flag = True
                num_sti = idx
                num_edi = idx
            else:
                num_edi = num_edi if num_edi > idx else idx   
        elif flag: 
            break
    return num_sti, num_edi

def get_parse_str(file:str):
    num_sti, num_edi = parse(file)
    head = ""
    number = ""
    tail = ""
    
    
    if num_sti == -1:
        head = file
        number = "0"
        tail = ""
    else:
        head = file[:num_sti]
        number = file[num_sti:num_edi+1]
        tail = file[num_edi+1:]

    head = head.lower()
    number = number.lstrip("0").strip()
    number = number if number else "0"
    tail = tail.strip()
    
    #print(f"{file} [{head}] | [{number}] | [{tail}]")
    return head, number, tail

def compare(a:str, b:str):
    a_head, a_num, a_tail = get_parse_str(a)
    b_head, b_num, b_tail = get_parse_str(b)
    
    # HEAD 기준 (HEAD 문자열 순)
    if a_head > b_head:
        return 1 
    elif a_head == b_head:
        # NUMBER 기준 (num 작은 순)
        if int(a_num) == int(b_num):
            return 0
        elif int(a_num) > int(b_num):
            return 1
        else:
            return -1
    elif a_head < b_head:
        return -1
    
def solution(files):
    answer = []
    files.sort(key=cmp_to_key(compare))
    answer = files.copy()
        
        
    return answer

'연습' 카테고리의 다른 글

DP 풀기 전 정독하기  (0) 2024.06.21
프로그래머스 상담원 인원  (0) 2024.06.20
프로그래머스 h-index  (0) 2024.06.17
python cmp_to_key (프로그래머스 가장 큰 수)  (0) 2024.06.17
EC2 Domain SSL  (0) 2024.05.27
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함