코딩 테스트/문제 풀기
[프로그래머스] 파일명 정렬
hazel_
2021. 4. 2. 20:15
programmers.co.kr/learn/courses/30/lessons/17686
방법 1
def solution(files):
file_info=[]
for index, file in enumerate(files):
# 파일이름, 숫자, 인덱스 저장
HEAD=''
tmp_NUM=''
NUMBER=''
TAIL=''
head_index=0
while not file[head_index].isnumeric():
HEAD+=file[head_index].lower()
head_index+=1
number_index=head_index
while number_index < len(file) and file[number_index].isnumeric() :
tmp_NUM+=file[number_index]
number_index+=1
if tmp_NUM[0]=='0' and len(tmp_NUM) > 1:
find_start=0
for i in range(0,len(tmp_NUM)):
if tmp_NUM[i] != '0':
break
else:
find_start+=1
if find_start==len(tmp_NUM):
NUMBER='0'
else:
NUMBER=file[head_index+find_start:number_index]
else:
NUMBER=tmp_NUM
TAIL = file[number_index:len(file)]
file_info.append([HEAD, NUMBER, TAIL, index])
print(file_info)
file_info.sort(key=lambda x: (x[0],int(x[1]),int(x[3])))
result=[]
for i in range(len(file_info)):
result.append(files[file_info[i][3]])
return result
방법 2
import re
def solution(files):
answer=[re.split(r"([0-9]+)",file) for file in files]
answer.sort(key=lambda x:(x[0].lower(), int(x[1])))
for i in range(len(answer)):
answer[i] = ''.join(answer[i])
return answer