문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
코드
from functools import cmp_to_key
def cmpFile(a,b):
if a[0].upper() > b[0].upper():
return 1
elif a[0].upper() < b[0].upper():
return -1
else:
if int(a[1]) > int(b[1]):
return 1
elif int(a[1]) < int(b[1]):
return -1
return 0
def solution(files):
answer = []
res=[]
for i in files:
head=0
number=0
for j in range(len(i)):
if head==0 and '0'<=i[j]<='9':
head=j
if head!=0 and number==0 and ('0'>i[j] or i[j]>'9'):
number=j
if(number==0):
number=len(i)
answer.append([i[:head],i[head:number],i[number:]])
answer.sort(key=cmp_to_key(cmpFile))
for head,number,tail in answer:
res.append(head+number+tail)
return res
풀이
- 파일명을 특정 기준을 따라 정렬해라
- head, number, tail 구역으로 나눈다.
- 나눈 파일명을 기준에 따라 정렬하기 위해 cmpFile함수를 작성하고 cmp_to_key를 사용해서 비교함수로 사용한다
- 정렬한 파일명을 다시 합쳐서 리턴한다.
특이사항
- 람다와 정규식을 사용해서 풀면 이정도로 줄일 수 있단다…
import re
def solution(files):
a = sorted(files, key=lambda file : int(re.findall('\\d+', file)[0]))
b = sorted(a, key=lambda file : re.split('\\d+', file.lower())[0])
return b
- 이게 파이썬이지…
'알고리즘' 카테고리의 다른 글
[프로그래머스] 짝지어 제거하기 python (0) | 2024.02.09 |
---|---|
[백준] 20920 영단어 암기는 괴로워 python (1) | 2024.02.05 |
[프로그래머스] 석유 시추 python (0) | 2024.01.31 |
[백준] 2304 창고 다각형 python (0) | 2024.01.23 |
[백준] 22233 가희와 키워드 python (1) | 2024.01.22 |