ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค [lv2] ํŒŒ์ผ๋ช… ์ •๋ ฌ ํŒŒ์ด์ฌ

2021. 7. 25. 11:31ใ†๐Ÿ”ฑ Algorithm

์ •๋‹ต ์ฝ”๋“œ

import re


def solution(files):
    filtered_files = [re.split("([0-9]+)", file) for file in files]
    sorted_files = sorted(filtered_files, key=lambda x: (x[0].lower(), int(x[1])))
    return [(''.join(s)) for s in sorted_files]
    

files = ["img12.png", "img10.png", "img02.png", "img1.png", "IMG01.GIF", "img2.JPG"]
solution(files)
>>> ['img1.png', 'IMG01.GIF', 'img02.png', 'img2.JPG', 'img10.png', 'img12.png']

 

๐Ÿ“• ์ •๊ทœ ํ‘œํ˜„์‹์œผ๋กœ ํ•„ํ„ฐ๋ง ํ›„ : filtered_files

def solution(files):

    filtered_files = [re.split("([0-9]+)", file) for file in files]
    print(fileted_files)
    >>> [['img', '12', '.png'], ['img', '10', '.png'], ['img', '02', '.png'], ['img', '1', '.png'], ['IMG', '01', '.GIF'], ['img', '2', '.JPG']]

์šฐ์„  head ์™€ number ๋ฅผ ๋‚˜๋ˆ ์•ผ ํ•ฉ๋‹ˆ๋‹ค. head ๋Š” ๋ฌธ์ž๋งŒ, number ๋Š” ์ˆซ์ž๋งŒ ๋“ค์–ด๊ฐ‘๋‹ˆ๋‹ค.

โžก๏ธ tail ๋ถ€๋ถ„์— number ๊ฐ€ ๋“ค์–ด ๊ฐˆ ์ˆ˜ ์žˆ์ง€๋งŒ, Head, Number ๋งŒ ๋‚˜๋ˆ„๋ฉด ๋˜๊ธฐ ๋•Œ๋ฌธ์— ์ด ๋ถ€๋ถ„์—๋งŒ ์ง‘์ค‘ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ •๊ทœ ํ‘œํ˜„์‹์„ ์ด์šฉํ•˜์—ฌ ์ˆซ์ž๊ฐ€ ๋“ค์–ด๊ฐ„ ๋ถ€๋ถ„์„ ๊ธฐ์ค€์œผ๋กœ ๋ถ„๋ฆฌํ•ฉ๋‹ˆ๋‹ค. 

 

๐Ÿ“— ๋žŒ๋‹ค์‹์œผ๋กœ ์ •๋ ฌ

def solution(files):

    filtered_files = [re.split("([0-9]+)", file) for file in files]

    sorted_files = sorted(filtered_files, key=lambda x: (x[0].lower(), int(x[1])))
    print(sorted_files)
    >>> [['img', '1', '.png'], ['IMG', '01', '.GIF'], ['img', '02', '.png'], ['img', '2', '.JPG'], ['img', '10', '.pn', '21', 'g'], ['img', '12', '.png']]

1๏ธโƒฃ ์ฒซ๋ฒˆ์งธ Head ์ •๋ ฌ

๋žŒ๋‹ค์‹๊ณผ sorted() ๋ฉ”์†Œ๋“œ๋ฅผ ์ด์šฉํ•˜์—ฌ ์ •๋ ฌ ์กฐ๊ฑด์„ ๊ตฌํ˜„ํ•  ์ˆ˜  ์žˆ์Šต๋‹ˆ๋‹ค.

์šฐ์„  filtered_files ์˜ ๋ชจ๋“  ์›์†Œ๋“ค์˜ ์ฒซ๋ฒˆ์งธ ์ธ์ž๋ผ๋ฆฌ ๋น„๊ต ํ›„ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค. (sorted()์˜ ์„ธ๋ฒˆ์งธ ์ธ์ž๋กœ reverese=True /False ์กฐ๊ฑด์„ ํ†ตํ•ด ์˜ค๋ฆ„์ฐจ์ˆœ/๋‚ด๋ฆผ์ฐจ์ˆœ์„ ์„ค์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค)

 

2๏ธโƒฃ ๋‘๋ฒˆ์งธ Number ์ •๋ ฌ

์ฒซ๋ฒˆ์งธ ์ธ์ž๋ผ๋ฆฌ์˜ ๋น„๊ต๋กœ head ๋ผ๋ฆฌ ๋น„๊ต๋ฅผ ๋งˆ์ณค๋‹ค๋ฉด, lambda ์˜ ๋‘๋ฒˆ์งธ ์ธ์ž๋กœ number ๋ฅผ ๋น„๊ตํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๐Ÿฆ ๋งŒ์•ฝ ๋ฌธ์ œ ์กฐ๊ฑด์ด number ๋Š” ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ์ด์—ˆ๋‹ค๋ฉด, int(x[1]) ์•ž์— - (minus) ๋ถ€ํ˜ธ๋ฅผ ๋ถ™์—ฌ ๋‚ด๋ฆผ์ฐจ์ˆœ์„ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ•ด๋‹น ๋ฌธ์ œ๋Š” ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ์ด๊ธฐ ๋•Œ๋ฌธ์— ๋ถ€ํ˜ธ๋ฅผ ์จ์ฃผ์ง€ ์•Š์•„๋„ ๋ฉ๋‹ˆ๋‹ค.