Cute Running Puppy

algorithm/[python] leetcode

[python] 937. Reorder Data in Log Files

R.silver 2022. 3. 26. 16:51
반응형

https://leetcode.com/problems/reorder-data-in-log-files/

 

Reorder Data in Log Files - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

기준에 맞추어 로그를 재정렬하는 문제 
1. 로그의 가장 앞 부분은 식별자
2. 문자로 구성된 로그가 숫자로 구성된 로그보다 앞에 온다
3. 식별자는 순서에 영향을 미치지 않는다, 문자가 동일할경우 식별자 순으로 정렬한다 
4. 숫자 로그는 입력 순서대로 정렬한다

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

        for log in logs:
            if log.split()[1].isdigit():
               digit.append(log)
            else:
                alpha.append(log)
        alpha.sort(key=lambda x:(x.split()[1:],x.split()[0]))
        return alpha + digit

 

split()와 lambda를 사용

1. split()을 사용하여 식별자 뒤의 글자가 숫자인지 문자인지 판단한다 

2. 숫자이면 digit 리스트에 넣고 문자이면 alpha 리스트에 넣는다. 

3. alpha를 람다식을 사용하여 정렬한다. 

    a. 로그 뒤의 문자를 key로 하여 정렬

    b. 동일한 경우 후순위로 식별자 [0]를 지정해 정렬

4. alpha 와 digit을 + 연산자를 사용하여 붙인다.

반응형

'algorithm > [python] leetcode' 카테고리의 다른 글

[python] 15. 3sum  (0) 2022.08.02
[python] 1. Two Sum  (0) 2022.07.24
[python]5. Longest Palindromic Substring  (0) 2022.07.24
[python] 344. Reverse String  (0) 2022.03.26
[python] 125. Valid Palindrome  (0) 2022.03.19