기억은 짧고 기록은 길다
[프로그래머스/Programmers] [3차] 파일명 정렬 - Python 본문
Link
코딩테스트 연습 - [3차] 파일명 정렬
파일명 정렬 세 차례의 코딩 테스트와 두 차례의 면접이라는 기나긴 블라인드 공채를 무사히 통과해 카카오에 입사한 무지는 파일 저장소 서버 관리를 맡게 되었다. 저장소 서버에는 프로그램
programmers.co.kr
Solution
해당 문제는 number_check을 기준으로 if문을 구성하면 해결되는 문제였다.
숫자가 나오기 전까지는 head에 더해주고 (number_check == 0)
숫자가 나오면 number에 더해주고 (number_check = 1)
다시 문자가 나오면 tail에 나머지를 모두 추가해준다. (number_check == 1 and not isdigit())
def solution(files):
answer = []
for i in range(len(files)):
head, number, tail = '', '', ''
number_check = 0
for j in range(len(files[i])):
if number_check == 0 and not files[i][j].isdigit():
head += files[i][j]
elif files[i][j].isdigit():
number += files[i][j]
number_check = 1
elif not files[i][j].isdigit() and number_check == 1:
tail += files[i][j:]
break
answer.append((head, number, tail))
answer.sort(key=lambda x: (x[0].lower(), int(x[1])))
return [''.join(answer[i]) for i in range(len(answer))]
🔑 key point:
if number_check == 0 and not files[i][j].isdigit():
elif files[i][j].isdigit():
elif not files[i][j].isdigit() and number_check == 1:
📌 Tip: answer.sort(key=lambda x: (x[0].lower(), int(x[1])))
Other Solution
해당 문제는 정규표현식을 사용하면 간단하게 해결되는 문제였다.
필자는 정규표현식을 활용해본 경험이 부족해 이 문제를 정규표현식으로 해결하지 않았지만 이 글을 읽는 사람들은 하단에 첨부되어 있는 글과 함께 정규표현식을 익혀가길 바란다.
import re
def solution(files):
a = sorted(files, key=lambda file : int(re.findall('\d{1,5}', file)[0]))
b = sorted(a, key=lambda file : re.split('\d{1,5}', file.lower())[0])
return b
🔑 key point: Regular Expression
첨부
'CodingTest > programmers' 카테고리의 다른 글
| [프로그래머스/Programmers] 괄호 회전하기 - Python (0) | 2021.11.10 |
|---|---|
| [프로그래머스/Programmers] n^2 배열 자르기 - Python (1) | 2021.11.05 |
| [프로그래머스/Programmers] 수식 최대화 - Python (0) | 2021.10.08 |
| [프로그래머스/Programmers] 오픈채팅방 - Python (0) | 2021.10.07 |
| [프로그래머스/Programmers] 영어 끝말잇기 - Python (0) | 2021.10.06 |
Comments