Algorithm/ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€

[ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€ / Python파이썬] νŠœν”Œ

meeeeejin 2021. 5. 15. 11:00

문제 링크: https://programmers.co.kr/learn/courses/30/lessons/64065

 

μ½”λ”©ν…ŒμŠ€νŠΈ μ—°μŠ΅ - νŠœν”Œ

"{{2},{2,1},{2,1,3},{2,1,3,4}}" [2, 1, 3, 4] "{{1,2,3},{2,1},{1,2,4,3},{2}}" [2, 1, 3, 4] "{{4,2,3},{3},{2,3,4,1},{2,3}}" [3, 2, 4, 1]

programmers.co.kr

 

 

문제 μ„€λͺ…

νŠœν”Œ (a1, a2, a3, a4)λ₯Ό ν‘œν˜„ν•˜λŠ” 집합을 μ›μ†Œμ˜ κ°œμˆ˜κ°€ μž‘μ€ μˆœμ„œλŒ€λ‘œ μ •λ ¬ν•˜λ©΄ {{a1}, {a1, a2}, {a1, a2, a3}, {a1, a2, a3, a4}}κ°€ λ©λ‹ˆλ‹€. μ΄λ•Œ μ§‘ν•©μ—μ„œ νŠœν”Œμ„ κ΅¬ν•˜λŠ” 방법은, {ai} = s[i] - s[i - 1] μž…λ‹ˆλ‹€. (νŽΈμ˜μƒ 인덱슀λ₯Ό 1λΆ€ν„° μΉ΄μš΄νŠΈν–ˆμŠ΅λ‹ˆλ‹€. ) 예λ₯Ό λ“€μ–΄ iλŠ” 3일 λ•Œ, s[3] - s[2] = {a1, a2, a3} - {a1, a2} = {a3}μž…λ‹ˆλ‹€. 

 

λ”°λΌμ„œ 주어진 s의 μ›μ†Œλ“€μ„ λ¦¬μŠ€νŠΈμ— λ‹΄μ•„μ„œ μ›μ†Œ(집합)의 κ°œμˆ˜κ°€ μž‘μ€ μˆœμ„œλŒ€λ‘œ μ •λ ¬ν•©λ‹ˆλ‹€. {ai} = s[i] - s[i - 1]을 μ΄μš©ν•΄μ„œ νŠœν”Œμ˜ μ›μ†Œλ₯Ό μ•žμ—μ„œλΆ€ν„° κ΅¬ν•©λ‹ˆλ‹€. 

λ¬Έμžμ—΄ ν˜•νƒœλ₯Ό 리슀트둜 λ³€ν™˜ν•˜κΈ° μœ„ν•΄μ„œ ast.literal_eval()을 μ‚¬μš©ν–ˆμŠ΅λ‹ˆλ‹€. 

 

 

 

 

μ†ŒμŠ€μ½”λ“œ

import ast

def solution(s):
    answer = []
    s = "[" + s[1:-1] + "]"
    s = ast.literal_eval(s)         # s의 μ›μ†Œλ“€μ„ 리슀트둜 λ³€ν™˜ν•˜μ—¬ μ €μž₯
    s.sort(key=lambda x: len(x))    # μ›μ†Œμ˜ κ°œμˆ˜κ°€ μž‘μ€ μˆœμ„œλŒ€λ‘œ s μ •λ ¬
    
    answer.append(list(s[0])[0])
    for i in range(0, len(s) - 1):
        answer.append(list(s[i + 1] - s[i])[0])

    return answer

 

 

 

728x90