[프로그래머스](python)(해시) 완주하지 못한 선수

berry ·2021년 4월 22일
0

Algorithm

목록 보기
3/77
post-thumbnail

문제


내 풀이

def solution(participant, completion):
	participant.sort()
	completion.sort()
	answer = ''

    for i in participant:
        if i not in completion:
            participant.append(i)

        break

    return participant[-1]
    

결과

마지막 문제를 계속 통과하지 못했다....
왜 안될까..?🥲
얼른 눈물을 닦고 구글링


나와 비슷한 풀이

def solution(participant, completion):
    participant.sort()
    completion.sort()
    for i in range(len(completion)):
        if participant[i] != completion[i]:
            return participant[i]
    return participant[len(participant)-1]

처음에 participant[i]와 비교하도록 짰었는데 마무리가 문제였다.
하나 발견하면 바로 for문을 빠져나가 return 하므로 완주 못한 사람이 한 명이라 가능한 것 같다. 두 명 이상이면 안 될 듯!
sort로 정렬해서 맞지 않는 index만 찾아주면 하나의 잘못된 값을 찾은 것이니 전제 하에 효율성이 좋은 것 같다.

+++
len(completion)
: completion에 저장된 항목이 몇 개인지 확인



다른 풀이

import collections

def solution(participant, completion):
	answer = collections.Counter(participant) - collections.Counter(completion)
	return list(answer.keys())[0]

+++
사용된 모듈
1. collections
.Count()
: 컨테이너에 동일한 값의 자료가 몇 개 들어가있는지!

  1. collections.Counter()
  • Dictionary 형태로 출력
  • 산술/집합 연산이 가능 (Counter 객체!)

예) collections.Counter(a) - collections.Counter(b)
: a - b 의 값 도출

+++
dictionary 형태로 출력_ dictionary로부터 key값을 구하고 싶다면
a.keys()

를 리스트로 만들고 싶다면
list(a.keys())



다른 풀이 2

def solution(participant, completion):
    answer = ''
    temp = 0
    dic = {}
    for part in participant:
        dic[hash(part)] = part
        temp += int(hash(part))
    for com in completion:
        temp -= hash(com)
    answer = dic[temp]

    return answer

+++
Hash
hash(part)로 hash를 받고 int(hash(part))로 hash(part)들을 모두 더한 후 temp에 저장, temp에서 hash(com)을 빼줌
그리고 다시 dictionary로 저장

profile
Engineer

0개의 댓글