[LeetCode] Reorder Data in Log Files

yoonene·2022년 12월 19일
0

알고리즘

목록 보기
30/62

문제 이동
난이도 : ⭐️

첫 번째 제출

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

        for log in logs:
            l = log.split()
            if l[1].isdigit():
                num_lst.append(l)
            else:
                str_lst.append(l)

        str_lst.sort(key=lambda x:(x[1:], x[0]))
        str_lst.extend(num_lst)
        result = [' '.join(log) for log in str_lst]
        return result

Runtime : 45 ms
Memory : 14.1 MB

두 번째 제출

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

        for log in logs:
            if log.split()[1].isdigit():
                num_lst.append(log)
            else:
                str_lst.append(log)

        str_lst.sort(key=lambda x:(x.split()[1:], x.split()[0]))
        return str_lst + num_lst

Runtime : 34 ms
Memory : 14 MB

두 번째 제출 코드는 굳이 split한 리스트를 원소로 사용한 이중리스트를 다룰 필요없이 그냥 그때그때 split 부르는 식으로 바꿨다.

split 안한 log 하나가 원소니까 join할 필요가 없어졌다.

extend 대신 '+' 로 두 리스트를 합쳤다.


+)

배운 점

  • key=lambda를 활용한 sort를 할 때 다중조건을 어떻게 주는지 알게 되었다.
    str_lst.sort(key=lambda x:(x[1:], x[0]))
  • '1'과 같이 타입이 string이지만 내용은 숫자인 경우, isdigit()을 사용하면 된다. (문자인지 알고 싶으면 isalpha()가 있다.)
profile
NLP Researcher / Information Retrieval / Search

0개의 댓글