[Python] 완주하지 못한 선수
1번 풀이 : for-else문 활용
def solution(participant, completion):
participant = sorted(participant)
completion = sorted(completion)
for i in range(0,len(participant)-1):
if participant[i] != completion[i]:
no = participant[i]
break
else:
no = participant[len(participant)-1]
#print(no)
answer = '' + no
return answer
- 다른 언어였다면,
- no객체를 미리 선언해놓고, 반복문이 끝난 후, if문을 작성해 no == ''를 확인 후 리스트의 마지막 원소를 no에 할당했어야 했을 것이다.
- 하지만, 파이썬은 for-else문을 지원한다
- 리스트의 길이 N 이하만큼 반복문이 돌게 되므로 아래의 Counter활용보단 아니지만, 비교적 효율적이다.
2번 풀이 : Counter 객체의 마이너스(-) 연산활용
def solution(participant, completion):
from collections import Counter
p_c = Counter(participant)
c_c = Counter(completion)
diff = p_c - c_c
answer = '' + list(diff.keys())[0]
return answer
- 문제에서 미완주자가 1명뿐이라는 큰 힌트를 줬기 때문에,
- 6번째 줄의 인덱싱을 위와 같이 [0]으로 할 수 있었다.
※ Dictionary 객체가 아닌 Counter 객체이기 때문에 마이너스 연산이 가능한 것임을 기억해야 한다.
'프로그래머스 > [코테]Level1' 카테고리의 다른 글
[Python] 2016년 (0) | 2020.09.03 |
---|---|
[Python] 가운데 글자 가져오기 (0) | 2020.09.03 |
[Python] 같은 숫자는 싫어 (0) | 2020.09.03 |
[Python] 체육복 (0) | 2020.07.06 |
[Python] 모의고사 (0) | 2020.07.05 |