문제 : https://school.programmers.co.kr/learn/courses/30/lessons/12981
📜 접근 방법
찾아야 하는 것 : 가장 먼저 탈락하는 사람과 그 사람이 몇 번째 차례에 탈락하는지
조건 : 이미 말했던 단어를 말하는 경우, 이전 단어의 끝문자와 현재 단어의 첫 문자가 같지 않는 경우
- 주어진 단어 갯수만큼 반복
- dict_에 단어가 없거나 이전 단어 끝 문자와 현재 단어 첫 문자가 같으면
- dict_에 넣어주고 저장한 끝 문자를 변경
- 가장 먼저 탈락하는 사람과 몇번째 차례에 탈락하는지 구한다
- dict_에 단어가 없거나 이전 단어 끝 문자와 현재 단어 첫 문자가 같으면
❌ 실패 코드
round 함수를 썼는데 사사오입 원칙으로 인해 제대로 숫자가 변하지 않는 오류 발생
사사오입 원칙 : https://chipndale.tistory.com/5
import math
def solution(n, words):
answer = []
dict_ = {}
i = 0
last_word = words[0][0]
while i < len(words):
if words[i] not in dict_ and last_word == words[i][0]:
dict_[words[i]] = 1
last_word = words[i][-1]
else:
# 사사오입 원칙으로 인해 2.5는 2로 됨
play = round((i + 1) / n)
play = int(play)
num = i % n + 1
answer.append(num)
answer.append(play)
return answer
i += 1
return [0, 0]
✅ 정답 코드
def solution(n, words):
answer = []
dict_ = {}
i = 0
last_word = words[0][0]
while i < len(words):
if words[i] not in dict_ and last_word == words[i][0]:
dict_[words[i]] = 1
last_word = words[i][-1]
else:
play = (i + 1) / n
if play > (i + 1) // n:
play += 1
play = int(play)
num = i % n + 1
answer.append(num)
answer.append(play)
return answer
i += 1
return [0, 0]
💡알게 된점
웬만하면 파이썬에선 round함수를 쓰지 말아야겠다.
'코딩테스트 > Python' 카테고리의 다른 글
[python] 프로그래머스 주식가격 (1) | 2023.04.25 |
---|---|
[python] 프로그래머스 괄호 회전하기 (0) | 2023.04.24 |
[python] 프로그래머스 올바른 괄호 (0) | 2023.04.21 |
[python] 프로그래머스 콜라 문제 (0) | 2023.04.19 |
[python] 프로그래머스 호텔 대실 (0) | 2023.04.16 |