본문 바로가기
코딩테스트/Python

[python] 프로그래머스 영어 끝말잇기

by nahkim 2023. 4. 22.

문제 : https://school.programmers.co.kr/learn/courses/30/lessons/12981

📜 접근 방법

찾아야 하는 것 : 가장 먼저 탈락하는 사람과 그 사람이 몇 번째 차례에 탈락하는지

조건 : 이미 말했던 단어를 말하는 경우, 이전 단어의 끝문자와 현재 단어의 첫 문자가 같지 않는 경우

  1. 주어진 단어 갯수만큼 반복
    1. dict_에 단어가 없거나 이전 단어 끝 문자와 현재 단어 첫 문자가 같으면
      1. dict_에 넣어주고 저장한 끝 문자를 변경
    2. 가장 먼저 탈락하는 사람과 몇번째 차례에 탈락하는지 구한다

 

❌ 실패 코드

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함수를 쓰지 말아야겠다.