daco2020 2022. 2. 13. 09:42

문제 설명

Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.

It should remove all values from list a, which are present in list b keeping their order.

array_diff([1,2],[1]) == [2]

If a value is present in b, all of its occurrences must be removed from the other:

array_diff([1,2,2,2,3],[2]) == [1,3]

 

 

해결 방법

1. b리스트 안의 요소가 a리스트 안에 있는지 확인한다.

2. 있다면 해당 요소를 a리스트에서 삭제한다.

 

def array_diff(a, b):
    for i in b:
        while i in a:
            a.remove(i)
    return a

이렇게 풀 수도 있고

 

 

다음 처럼 컴프리핸션으로 풀 수 도 있다!

def array_diff(a, b):
    return [x for x in a if x not in b]