[프로그래머스/파이썬] Level 2 튜플

bye9·2021년 4월 10일
0

알고리즘(코테)

목록 보기
107/130

https://programmers.co.kr/learn/courses/30/lessons/64065


문제풀이

{,}를 start,end로서 받아, 문자열 "{{2},{2,1},{2,1,3},{2,1,3,4}}"에서 길이를 기준으로 오름차순해서 array=['2', '2,1', '2,1,3', '2,1,3,4']로 변환해준다.

array에서 ,를 기준으로 분할하여 array2=[['2'], ['2', '1'], ['2', '1', '3'], ['2', '1', '3', '4']]로 만들어준다.

이제 각 리스트를 돌면서 안들어간 값만 차례대로 넣어준다.

더 간단한 코드의 경우 ['2', '2,1', '2,1,3', '2,1,3,4']로 변환해주는 과정을
s1 = s.lstrip('{').rstrip('}').split('},{')으로 단순화 가능하다.

그 이후의 작업은 동일하다.

소스코드

def solution(s):
    start,end=-1,0
    array=[]
    temp=[]
    for i in s:
        if i=="{":
            start+=1
        elif i=="}":
            end+=1
            if start==end:
                array.append("".join(temp))
                temp=[]
        else:
            if start>end:
                temp.append(i)
    array=sorted(array, key=lambda x:len(x))
    #print(array)
    
    array2=[]
    for i in array:
         array2.append(list(i.split(",")))
    
    #print(array2)
    result=[]
    for i in array2:
        for j in i:
            if int(j) not in result:
                result.append(int(j))
    return (result)

더 간단한 코드

def solution(s):
    answer = []

    s1 = s.lstrip('{').rstrip('}').split('},{')
    #print(s1)

    new_s = []
    for i in s1:
        new_s.append(i.split(','))

    new_s.sort(key = len)

    for i in new_s:
        for j in range(len(i)):
            if int(i[j]) not in answer:
                answer.append(int(i[j]))

    return answer

0개의 댓글