Skip to main content
Overview

[Programmers] Filename Sort

November 2, 2021
1 min read

https://programmers.co.kr/learn/courses/30/lessons/17686

Approach 1

We need to split filenames based on numeric characters. One way is to implement it manually:

number_list = [str(i) for i in range(10)]
for idx in range(len(files)):
head, number, tail = "", "", ""
number_idx, tail_idx = -1, -1
# Find the start index of the number part
for j in range(len(files[idx])):
if files[idx][j] in number_list:
head = files[idx][:j]
# print(head)
number_idx = j
break
# Find the start index of the tail part
for j in range(number_idx, len(files[idx])):
if files[idx][j] not in number_list:
number = int(files[idx][number_idx:j])
break
tail = files[idx][j:]
files[idx] = [head, number, tail]

Midway through implementing this, I remembered regex. Since \d can distinguish digits, we can do:

re.compile(r'(\d+)')

Since we only need to split, I used re.split.

For sorting, passing the priority to the sort function handles everything. Since we only need to sort by head and number, I pass this lambda as the sort key:

lambda x: (x[0].lower(), int(x[1]))

Approach 2

Apparently you could also use Java’s Comparable interface for this. In Python, you’d implement __cmp__, though there’s no real reason to use it for this problem. It might be useful if the sorting logic were more complex.

Code

https://github.com/naem1023/codingTest/blob/master/sort/pg-30-17686.py

Loading comments...