본문 바로가기
Programming/Contest

[checkio] Non-unique Elements

by NAMP 2016. 4. 5.

[checkio] Non-unique Elements

기본코드

#Your optional code here
#You can import some modules or create additional functions

def checkio(data):
    #Your code here
    #It's main function. Don't remove this function
    #It's used for auto-testing and must return a result for check.

    #replace this for solution
    return data

#Some hints
#You can use list.count(element) method for counting.
#Create new list with non-unique elements
#Loop over original list

if __name__ == "__main__":
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert isinstance(checkio([1]), list), "The result must be a list"
    assert checkio([1, 2, 3, 1, 3]) == [1, 3, 1, 3], "1st example"
    assert checkio([1, 2, 3, 4, 5]) == [], "2nd example"
    assert checkio([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5], "3rd example"
    assert checkio([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9], "4th example"

소스 작성

def checkio(data): 함수만 작성합니다.

def checkio(data):
    rst = []
    for d1 in data:
        cnt = 0
        for d2 in data:
            if d1 == d2 :
                cnt = cnt+1
        if cnt != 1 :
            rst.append(d1)

    ##print(rst)
    return rst

이중 for 루프를 돌면서 같은 값이 있는지 비교합니다. 자신과의 비교가 있으므로 무조건 1이상이 됩니다. (비교 코드가 정확하다면) 전체 비교 후 같은 수의 값이 1이 아닌 것은 non-unique 이므로 배열에 추가하여, 반환합니다.

Precondition:
0 < len(data) < 1000

하지만 리스트의 크기가 커지면 시간이 오래 걸리는 단점이 있습니다.

Shortest 코드는 아래와 같습니다.

checkio=lambda d:[x for x in d if d.count(x)>1]

lambda 를 사용하여 표현합니다.
def f(x): ... --> f=lambda x: ...

참고

'Programming > Contest' 카테고리의 다른 글

[checkio] House password  (0) 2016.04.07
[checkio] Median  (0) 2016.04.06
[codingame] The Descent  (0) 2014.12.13
[codingame] Power of Thor  (0) 2014.12.13
[codingame] Onboarding  (0) 2014.12.13

댓글