[파이썬] 프로그래머스 : 파일명 정렬 (Lv.2)
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
0. 방향성 생각
문자열 나눠주고 하란대로 하기.
딕셔너리에 저장해서 밸류 정렬 후 키 가져오기.
1. 문자열 나누기
def solution(files):
num = set(['0','1','2','3','4','5','6','7','8','9'])
table = {}
for n,file in enumerate(files):
a,temp = True,[]
for idx,val in enumerate(file):
if a and val in num:
start = idx
a = False
elif not a and val not in num:
end = idx
break
else:
end = len(file)
방법은 여러가지겠지만 number 시작하는 부분과 끝나는 부분 체크.
예제 F-15처럼 tail이 없을수도 있으니까 for - else문으로 tale이 없는 경우 end 값 할당하기
n은 리스트에서 들어오는 인덱스. 추후 조건 head number가 같으면 정렬조건 만족을 위해 쓴 부분
2. 문자열 조건 맞추기
temp.extend([file[:start],file[start:end],file[end:]])
temp[0] = temp[0].lower()
temp[1] = temp[1].lstrip('0')
if temp[1] == '' :
temp[1] = '0'
temp[1] = int(temp[1])
temp.append(n)
table[file] = temp
head의 대문자는 모두 소문자로
number는 lstrip으로 왼쪽 모두 제거. 0부터 시작할 수 있으니 이 부분 체크하기.
이후에 temp에 파일 인덱스 추가해주기
끝났으면 딕셔너리에 저장
3. 정렬하기
answer = []
answer = list(table.items())
answer.sort(key=lambda x:(x[1][0],x[1][1],x[1][3]))
result = []
for i in answer:
result.append(i[0])
return result
head number 파일 인덱스 순으로 정렬하면 된다.
전체코드
def solution(files):
num = set(['0','1','2','3','4','5','6','7','8','9'])
table = {}
for n,file in enumerate(files):
a,temp = True,[]
for idx,val in enumerate(file):
if a and val in num:
start = idx
a = False
elif not a and val not in num:
end = idx
break
else:
end = len(file)
temp.extend([file[:start],file[start:end],file[end:]])
temp[0] = temp[0].lower()
temp[1] = temp[1].lstrip('0')
if temp[1] == '' :
temp[1] = '0'
temp[1] = int(temp[1])
temp.append(n)
table[file] = temp
answer = []
answer = list(table.items())
answer.sort(key=lambda x:(x[1][0],x[1][1],x[1][3]))
result = []
for i in answer:
result.append(i[0])
return result
코멘트
예외처리가 좀 빡셌음
'Algorithm > etc' 카테고리의 다른 글
[파이썬] 프로그래머스 : 순위 검색 (Lv.2) (0) | 2023.07.17 |
---|---|
[파이썬] 프로그래머스 : 메뉴 리뉴얼 (Lv.2) (0) | 2023.07.15 |
[파이썬] 프로그래머스 : 오픈채팅방 (Lv.2) (0) | 2023.07.15 |
[파이썬] 프로그래머스 : 방문 길이 (Lv.2) (0) | 2023.07.11 |
[파이썬] 프로그래머스 : 테이블 해시 함수 (Lv.2) (0) | 2023.07.11 |
[파이썬] 프로그래머스 : n^2 배열 자르기 (Lv.2) (0) | 2023.07.10 |
[파이썬] 프로그래머스 : 카펫 (Lv.2) (0) | 2023.07.10 |
댓글