# Reorder Data in Log Files in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have an array of logs. In that array each entry is a space delimited string of words. The first word in each log is an alphanumeric identifier. Then, there are different types of strings like below −

1. Each word after the id will consist only of lowercase letters;
2. Each word after the id will consist only of digits.

We will call these two types of logs as letter-logs and digit-logs respectively. And ti is guaranteed that each log has at least one word after its id.

We have to reorder the logs so that all of the letter-logs stays before any digit-log. And the letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties. Finally, the digit-logs should be put in their original order. So we have to return the final order of the logs.

So, if the input is like logs = ["dig1 9 2 5 2","let1 art can","dig2 4 8","let2 own kit dig","let3 art zero"], then the output will be ["let1 art can","let3 art zero","let2 own kit dig","dig1 9 2 5 2","dig2 4 8"]

To solve this, we will follow these steps −

• words := a new list
• nums := a new list
• for each log in logs, do
• s := a list of words of log
• if second word is a digit, then
• insert log at the end of nums
• otherwise,
• join each element of s by separating with spaces and insert into words array at the end
• words = Then sort the words array lexicographically
• words := join each element of words array by separating with spaces and make a list of strings
• merge two lists words and nums, then return

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def reorderLogFiles(self, logs):
words = []
nums = []
for log in logs:
s = log.split()
if s[1].isdigit():
nums.append(log)
else:
words.append((s[0], ' '.join(s[1:])))
words = sorted(words, key=lambda x: (x[1],x[0]))
words = [' '.join(w) for w in words]
return words + nums
ob = Solution()
print(ob.reorderLogFiles(["dig1 9 2 5 2","let1 art can","dig2 4
8","let2 own kit dig","let3 art zero"]))

## Input

["dig1 9 2 5 2","let1 art can","dig2 4 8","let2 own kit dig","let3 art zero"]

## Output

['let1 art can', 'let3 art zero', 'let2 own kit dig', 'dig1 9 2 5 2', 'dig24 8']
Updated on 06-Jul-2020 09:10:04

Advertisements