코딩문제
완주하지 못한 선수(프로그래머스 코딩테스트 연습) 파이썬
페어팩
2020. 7. 30. 16:48
#나의 풀이
# 1차 시도
def solution(participant, completion):
answer = ''
participant.sort()
completion.sort()
for i in range(len(participant)):
if i == len(participant)-1:
answer = participant[i]
break
else:
if participant[i] != completion[i]:
answer = participant[i]
break
return answer
답에 1명만 완주를 하지 못했다고 써있었기 때문에 가능했던 코드가 아니었나 싶다.
# 다른사람들의 풀이1
# collections 모듈을 이용한 풀이
import collections
def solution(participant, completion):
answer = collections.Counter(participant) - collections.Counter(completion)
return list(answer.keys())[0]
collections 모듈에 대해 몰랐던 나는 전혀 생각할 수 없었던 풀이방식
Counter() 함수는 리스트 값을 key값으로 설정하고 각각의 개수를 세는 함수인데, 연산이 가능하다.
# 풀이 디버그 및 값 해설
participant = ['mislav', 'stanko', 'mislav', 'ana']
completion = ['stanko', 'ana', 'mislav']
print(collections.Counter(participant))
# Counter({'mislav': 2, 'stanko': 1, 'ana': 1})
print(collections.Counter(completion))
# Counter({'stanko': 1, 'ana': 1, 'mislav': 1})
print(collections.Counter(participant) - collections.Counter(completion))
# Counter({'mislav' : 1})
# 다른사람들의 풀이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
어떻게 보면 해시의 의미를 잘 알고 있는 멋진 풀이법인 것 같다.
# 풀이 해설
participant = ["leo", "kiki", "eden"]
completion = ["eden", "kiki"]
# 딕셔너리에 해시값을 키로 값을 저장
dic = {-107385341409178503: 'leo', 3616655737638640184: 'kiki', -638437918834160338: 'eden'}
# for문을 통해 participant의 해시값(temp)들을 더함
temp = 2870832477395301343
# 다시 for문을 통해 temp값에서 completion의 해시값들을 빼줌
temp = -107385341409178503
# 모든 연산이 끝나고 남은 temp값을 key로 가지고 있는 값이 완주하지 못한사람
-107385341409178503 = 'leo'