알고리즘

[CodeWars] 6Kyu : Unique In Order

또롱또 2024. 12. 8. 13:31
728x90

https://www.codewars.com/kata/54e6533c92449cc251001667/train/python

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

이번에는 들어오는 인자값으로 한 케릭터씩 봤을떄 중복이 되면 안된다. 대소문자는 유니크하게 치는거 같다.

 

바로 직전문제가 set이나 count로 하는 방법을 써서 중복을 날렸지만, 이번에는 인접한 애들끼리만 비교를 해야하는거다.

 

들어오는건 배열일수도, 문자열일수도 있어보인다.

 

아래처럼 해봤다, result의 마지막이 sequence의 엘리멘트와 다르면 추가한다.

def unique_in_order(sequence):
    result = []
    for ele in sequence:  
        if not result or result[-1] != ele:  
            result.append(ele)
    return result

 

정답은 나랑 같은것도 있었지만 아래와 같다.

 

def unique_in_order(iterable):
    result = []
    prev = None
    for char in iterable[0:]:
        if char != prev:
            result.append(char)
            prev = char
    return result

 

None을 저렇게 빈값을 넣어줄수도 있구나 싶다. 그리고는 그냥 내꺼랑 비슷하다, interable을 for로 돌려서 안에가 다르면 집어넣고, 그리고 None으로 아까 선언한걸 char로 바꿔주고, 반복이다. 슬라이싱하는 [0: ]는 없어도 되보이긴한다.

728x90