기억보다 기록을

[leetcode] Reorder Data in Log Files (python) 본문

Algorithm/Leet code

[leetcode] Reorder Data in Log Files (python)

juyeong 2023. 2. 21. 17:43
반응형

Q. You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.

There are two types of logs:

  • Letter-logs: All words (except the identifier) consist of lowercase English letters.
  • Digit-logs: All words (except the identifier) consist of digits.

Reorder these logs so that:

  1. The letter-logs come before all digit-logs.
  2. The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
  3. The digit-logs maintain their relative ordering.

Return the final order of the logs.

 

Idea: :

The first word is identifier, Order: letters(sorted lexicographically) + digits(maintaining original order)

1. check each word to check whether letters or digits

2. sorting it without Identifier

3. add digits array after letters array

-배열 인덱스 1부터 체크해야겠다 

-배열 2개를 선언한다 하나는 letters를 담을거고 하나는 digits 모으기

-그럼 우선 문자열/ 정수 인지 구분이 필요하다 -> isalpha 함수 써보자 

 

 

A. 

if문에 log.split()[1]가 유효한 이유는, 배열이 숫자+문자 조합이 아니라(식별자 제외), 문자열끼리/ 숫자열끼리로 나누어져있기 때문이다.

그래서 line5에서 인덱스1에 해당하는 값만을 체크한다.

digits 리스트는 더이상 체크하지 않고 마지막에 + 연산자로 맨 뒤에 추가한다

letters 리스트를 어떻게 정렬할지가 중요하한데 여기서 람다써서 하는게 kick point

class Solution:
    def reorderLogFiles(self, logs: List[str]) -> List[str]:
        letters , digits = [], []
        for log in logs:
            if log.split()[1].isalpha():
                letters.append(log)
            else:
                digits.append(log)
                
        letters.sort(key = lambda x: (x.split()[1:], x.split()[0]))
        return letters + digits

 

람다 참고: 

list.sort(key = lambda x : (x[0], x[1]))

비교할 요소가 2개. x[0]으로 오름차순 정렬하고, 그 다음에 x[1]로 정렬

-> x[0]이 같으면, x[1]을 기준으로 정렬

 

 

반응형