동캄의 코딩도장

프로그래머스 level2 [튜플] 파이썬 본문

코테/프로그래머스

프로그래머스 level2 [튜플] 파이썬

동 캄 2021. 12. 17. 17:32

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

#프로그래머스 튜플

def solution(s):
    answer = []
    i=1
    lst=[]
    while i<(len(s)-1):
        if s[i]=='{':
            arr=[]
            j=1
            while s[i+j]!='}':
                j+=1
            arr=list(map(int,s[i+1:i+j].split(',')))
            i+=j
            lst.append(arr)
        i+=1
    lst.sort(key=lambda x:(len(x)))
    for i in range(len(lst)):
        for j in range(len(lst[i])):
            if lst[i][j] not in answer:
                answer.append(lst[i][j])
    return answer

맨 처음과 끝을 제외하고, '{'로 시작하고, '}'로 끝날때 마다 분할하여, arr에 담는다.

이러한 arr을 담은 lst를 정렬하고 answer에 값을 하나씩 저장한다.

 

 

원래는 set을 이용하여 풀려고 하였는데, 반복되는 숫자가 존재하기 때문에 [ ex (2,3,1,2)] list로 값을 받아서 해결하였다.