728x90
반응형

재밌는 정렬 문제이다.

입력받을 때 리스트에 [문자열의 길이, 숫자의 합, 문자열]와 같은 방식으로 저장해주면 

lambda를 사용해서 매우 쉽게 정렬해줄 수 있다. 

def num(s):
    res = 0
    for c in s:
        if '0' <= c <= '9':
            res += int(c)
    return res

N = int(input())
li = []
for _ in range(N):
    s = input()
    li.append([len(s), num(s) , s])
li.sort(key=lambda x:x[2])
li.sort(key=lambda x:x[1])
li.sort(key=lambda x:x[0])
for t in li:
    print(t[-1])

좀 더 깔끔하게 짠 코드

def num(s):
    return sum([int(c) for c in s if '0' <= c <= '9'])

N = int(input())
li = []
for _ in range(N):
    s = input()
    li.append([len(s), num(s) , s])
li.sort(key=lambda x:(x[0], x[1], x[2]))
for t in li:
    print(t[-1])
728x90
반응형

+ Recent posts