- Published on
Reorder Log Files
- Authors
- Name
- Alex Noh
Problem
Reorder logs. Here are the rules.
- The first part of the log is the
identifier
. - A log that consists of alphabets comes before the ones with numbers.
- The identifier does not affect the order, but when the remaining characters are same, it should be sorted by the identifier.
- As for the number logs, you should maintain their relative order.
Examples
example.py
log1 = ["dig1 8 1 5 1", "let1 art can", "dig2 3 6", "let2 own kit dig", "let3 art zero"]
output1 = ["let1 art can", "let3 art zero", "let2 own kit dig", "dig1 8 1 5 1", "dig2 3 6"]
log2 = ["a1 9 2 3 1", "g1 act car", "zo4 4 7", "ab1 off key dog", "a8 act zoo"]
output2 = ["g1 act car", "a8 act zoo", "ab1 off key dog", "a1 9 2 3 1", "zo4 4 7"]
Things you should know
Lambda function
If you have used another programming languages that support lambda functions
Here's a good news. There also is one in Python too!
arrow-function.js
const add = (num1, num2) => num1 + num2;
lambda.py
# normal case
add = lambda num1, num2: num1 + num2
# when there is no argument
greeting = lambda: 'hello'
Sorting
You can easily sort a list using built-in sort function.
sorting.py
numbers = [3, 2, 1]
numbers.sort()
print(numbers) # [1, 2, 3]
But the thing is, this sort function changes the order of original list.
If you want the original to stay the same, You can use sorted
function.
sorting.py
numbers = [3, 2, 1]
new_numbers = sorted(numbers)
print(new_numbers) # [1, 2, 3]
print(numbers) # [3, 2, 1]
One more thing, let's assume you somehow want to sort a list of object.
You can do this by explicitly setting the key by which the list will be sorted.
Also you can sort in a reversed order by setting reverse=True
.
sorting.py
people = [
{
'name': 'sam',
'age': 30
},
{
'name': 'alex',
'age': 19
},
{
'name': 'john',
'age': 25
}
]
oldest_first = sorted(people, key=lambda x: x['age'], reverse=True)
print(oldest_first) # sam -> john -> alex
Solutions
main.py
def reorder_log_files(logs: List[str]) -> List[str]:
digits = []
letters = []
for log in logs:
if log.split()[1].isdigit():
digits.append(log)
else:
letters.append(log)
return sorted(letters, key=lambda x: (x.split()[1:], x.split()[0])) + digits