Python Algorithm Q3
Q3 Reorder-Data-in-log-Files
Q
You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.
There are two types of logs:
- Letter-logs: All words (except the identifier) consist of lowercase English letters.
- Digit-logs: All words (except the identifier) consist of digits. Reorder these logs so that:
- The letter-logs come before all digit-logs.
- The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
- The digit-logs maintain their relative ordering.
Return the final order of the logs.
Sample Input
Input: logs = [“dig1 8 1 5 1”,”let1 art can”,”dig2 3 6”,”let2 own kit dig”,”let3 art zero”] Output: [“let1 art can”,”let3 art zero”,”let2 own kit dig”,”dig1 8 1 5 1”,”dig2 3 6”]
Explanation: The letter-log contents are all different, so their ordering is “art can”, “art zero”, “own kit dig”. The digit-logs have a relative order of “dig1 8 1 5 1”, “dig2 3 6”.
Input: logs = [“a1 9 2 3 1”,”g1 act car”,”zo4 4 7”,”ab1 off key dog”,”a8 act zoo”] Output: [“g1 act car”,”a8 act zoo”,”ab1 off key dog”,”a1 9 2 3 1”,”zo4 4 7”]
Constraints
- 1 <= logs.length <= 100
- 3 <= logs[i].length <= 100
- All the tokens of logs[i] are separated by a single space.
- logs[i] is guaranteed to have an identifier and at least one word after the identifier.
1. My Solution -> Given Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
let: List[str] = []
dig: List[str] = []
for a in logs:
if a.split()[1].isdigit():
dig.append(a)
else:
let.append(a)
let.sort(key=lambda x:(x.split()[1:], x.split()[0])) #the most important part
return let+ dig
#for testing
s = Solution()
logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
s.reorderLogFiles(logs)
The sorting part using Lambda function is quite difficult. Can’t help shooting a look at the answer.
Let’s discuss shortly about lambda function in this solution. method function of list, the sort function takes ‘key=Function’ as a argument. You can write code like
“X.sort(key=FunctionName)”
The concept is simple. Put elements of list(X) to the function(FunctionName), and sort elements depends on the return of the function.
-
First of all, each of “let1 art can”,”let2 own kit dig”,”let3 art zero” is inserted in the function(lambda x:(x.split()[1:], x.split()[0])) as the argument x.
-
by ‘x.split()’, the first element(which is string) “let1 art can” is split into [[let1, art, can]]. Others as well.
-
by [1:], only “art can”, “own kit dig”, “art zero” left. And sorting starts between these elements.
-
Second return, x.split()[0], is the second basis for sorting when the same order occurs.
Overall Review
Just using lambda function, the code for the answer extremely shortened. Utilizing lambda well, my codes will be simple and better readable.