알고리즘

프로그래머스 영어 끝말잇기 [파이썬]

Brad Daeho Lee 2021. 6. 19. 11:18

문제

 

코딩테스트 연습 - 영어 끝말잇기

3 ["tank", "kick", "know", "wheel", "land", "dream", "mother", "robot", "tank"] [3,3] 5 ["hello", "observe", "effect", "take", "either", "recognize", "encourage", "ensure", "establish", "hang", "gather", "refer", "reference", "estimate", "executive"] [0,0]

programmers.co.kr

 

문제풀이

import math
def solution(n, words):
    answer = []
		#words에 첫번 째 idx에 있는 값을 넣어서 비교할 수 있게 한다.
    lst = [words[0]]
    cnt = 1
    
	#check를 넣은 이유는 끝까지 다 돌았는데 문제가 없는지 확인하기 위해서.
	#마지막에 끝말잇기가 틀릴 수도 있기 때문에 그걸 구분하기 위해서 사용함.
    check = True
    for i in range(1,len(words)):
        cnt += 1
        
		#words안에 i번째 단어의 첫번째 스펠링이랑 lst 마지막 단어의 마지막 스펠링이랑 같은지 비교한다.
        if words[i][0] == lst[-1][-1]:
            if words[i] not in lst:
                lst.append(words[i])
            else:
                check = False
                break
                
        else:
            check = False
            break
            
    #모든 단어 다 확인하고 끝까지 문제가 없었는지        
    if cnt == len(words) and check:
        answer = [0,0]
		#틀린게 있었으면
    else:
        x = cnt%n
        y = math.ceil(cnt/n)
        if x == 0:
            x = n
        answer = [x,y]        

    return answer