내가 하고 싶은 것들 중 하나

[프로그래머스] 완주하지 못한 선수 본문

알고리즘

[프로그래머스] 완주하지 못한 선수

여러가지이야기 2020. 5. 17. 20:14

아이콘 제작자 Skyclick from www.flaticon.com

from collections import Counter

def solution(participant, completion):
    answer = ''
    part_count = Counter(participant)
    part_count.subtract(completion)
    #for idx, value in part_count.items():
        #if value == 1:
            #answer += idx
    answer = [key for (key, value) in part_count.items() if value == 1][0]
    return answer
  • A와 B 리스트에서 중복되는 값을 지우고 남는 값이 무엇인지 구할 때 Counter classsubtract 매서드를 이용하면 된다.

  • collections 모듈에서 Counter class import하기

  • Counter 함수는 딕셔너리로 반환된다.

  • Counter 에는 subtract 매서드 가 내장되어 있다.

  • subtract 파이썬 공식문서 예시

    >>>c = Counter(a=4, b=2, c=0, d=-2)
    >>>d = Counter(a=1, b=2, c=3, d=4)
    >>>c.subtract(d)
    >>>c
    Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6}) 

https://docs.python.org/3/library/collections.html#collections.Counter

  • 새로 알게 된 것
A = [a, b, c, a]
B =[a, b, c]
>>>c = Counter(A)
>>>c.subtract(B) # B를 c와 같이 먼저 딕셔너리로 만들어주지 않고 리스트를 바로 넣어도 작동됨
>>>c
Counter({'a': 1, 'b': 0, 'c': 0}) 

'알고리즘' 카테고리의 다른 글

[프로그래머스] 숫자의 표현  (0) 2020.07.15
Comments