Tech Notes

Leetcode: Data Parsing

937. Reorder Data in Log Files

Solution 1:

class Solution:
    def reorderLogFiles(self, logs: List[str]) -> List[str]:
        letter_logs, digital_logs, res = [],[],[]

        def is_digit(content):
            return any(ch.isdigit() for ch in content)

        for index, log in enumerate(logs):
            identifier, content = log.split(" ")[0], "".join(log.split(" ")[1:])

            if is_digit(content):
                digital_logs.append(log)
            
            else:
                letter_logs.append([content, identifier, index])
        
        sorted_letter_logs = sorted(letter_logs)

        for data in sorted_letter_logs:
            res.append(logs[data[2]])

        return res + digital_logs

Solution 2: 1st watch how sorted function works in python: https://www.youtube.com/watch?v=D3JvDWO-BY4

class Solution:
    def reorderLogFiles(self, logs: List[str]) -> List[str]:

        def log_key(log):
            identifier, content = log.split(" ", maxsplit=1)
            if content[0].isalpha():
                return (0, content, identifier)
            else:
                return (1,)

        return sorted(logs, key=log_key)

2 log files were shared and asked to write program to create a report based on aggregated values of parsed input


Posted

in

by

Tags: