How to Reorder Data in Log Files using Python

1 min read 258 words

Let’s say that you have an array or a list, or logs.

Each of these logs is a space-delimited string of words.

For example:

logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]

The task is to reorder these logs and return them in the following acceptance criteria:

  • The first entry (identifier) of each log is ignored but still returned
  • The letter-logs are returned before the digit-logs
  • The identifier is only used to sort these there is a tie

How to analyse the problem

At first glance, this appears to be something that could be easily solved by looping through each log entry and if the second part of the entry is a string type, then adding it to a tempA list, otherwise adding it to a tempB list.

However, when it comes to the sorting part of the return type, this will get complicated fast.

Instead, it would be a much easier path to a resolution if we used the built-in sorted() Python function and created a custom sorting algorithm to address our acceptance criteria requirements.

How to code the solution

def reorderLogFiles(logs: List[str]) -> List[str]:

    def sorty(i):
        first, second = i.split(" ", 1)

        if second[0].isalpha():
            return [0, second, first]
        return [1,]

    return sorted(logs, key=sorty)

Analyse the time-space complexity

The time-space complexity is O(n) in this case, as we are simply filtering through a single list and returning new index reshuffling order, as opposed to breaking the original list into additional lists and looping through those, before completing the return.

Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags