LeetCode - The World's Leading Online Programming Learning Platform
문제 요약
from typing import List
class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
digit, letter = [], []
for log in logs:
if log.split()[1].isdigit():
digit.append(log)
else:
letter.append(log)
letter.sort(key=lambda x: (x.split()[1:], x.split()[0]))
return letter + digit
letter.sort(key=lambda x: (x.split()[1:], x.split()[0]))
처음에 숫자 로그도 정렬해야 하는 줄 알고 삽질을 신명나게 하다가 나중에 “maintain” 단어를 발견했다..ㅋ…
https://kingofbackend.tistory.com/98
삽질 로그
from typing import List
class Solution:
@staticmethod
def _separate_logs(logs: List[str]):
letter_log_list = list()
digit_log_list = list()
for log in logs:
word_list = log.split(" ")
if word_list[1][0].isdigit():
digit_log_list.append({word_list[0]: [int(digit) for digit in word_list[1:]]})
else:
letter_log_list.append({word_list[0]: [letter for letter in word_list[1:]]})
return digit_log_list, letter_log_list
@staticmethod
def _reorder_logs(log_list: List, is_digit=False) -> List[str]:
count = len(log_list)
for i in range(count):
for j in range(count - i - 1):
if is_digit:
if list(log_list[j].values()) < list(log_list[j + 1].values()):
log_list[j], log_list[j + 1] = log_list[j + 1], log_list[j]
else:
if (
list(log_list[j].values()) > list(log_list[j + 1].values())
or (
list(log_list[j].values()) == list(log_list[j + 1].values())
and list(log_list[j].keys()) > list(log_list[j + 1].keys())
)
):
log_list[j], log_list[j + 1] = log_list[j + 1], log_list[j]
return log_list
@staticmethod
def _convert_2_string(log_obj_list, is_digit=False):
log_list = list()
for log_obj in log_obj_list:
for idt, logs in log_obj.items():
if is_digit:
log_list.append(f"{idt} {' '.join(map(str, logs))}")
else:
log_list.append(f"{idt} {' '.join(logs)}")
return log_list
def reorderLogFiles(self, logs: List[str]) -> List[str]:
digit_log_list, letter_log_list = self._separate_logs(logs)
digit_log_list = self._reorder_logs(digit_log_list, True)
letter_log_list = self._reorder_logs(letter_log_list)
return self._convert_2_string(letter_log_list) + self._convert_2_string(digit_log_list, True)