[코딩테스트/프로그래머스/Python]단어 변환

Enter·2021년 7월 28일
0

코딩테스트

목록 보기
23/68

💡생각

  1. target이 words안에 있는지 확인.
  2. 없다면 0 retrun함.
  3. 있다면 words의 단어들을 deq에 다 넣음.
  4. deq에 단어들을 pop해서 begin단어와 비교한뒤 문자열의 한개만 다르고 target의 문자열과 두 개 이상 다를 경우 answer에 +1을 해주고 pop한 단어를 begin에 저장.
  5. 만약 pop한 단어가 begin단어와 비교한뒤 문자열의 한개만 다르고target과 한개만 다를 경우 answer에 +2 해주고 return해줌.



❓잘못된 코드1

테스트 케이스는 통과했지만 채점을 통과하지 못함.

문제점1. 질문하기를 보고
"begin : hot
target : lot
words = {"hot", "dot", "dog", "lot", "log"}
hot -> lot 으로 1번만에 가능함에도 불구하고
hot -> dot -> lot으로 변환하고 있는것이 아닌지 살펴보세요"
라고 해서 확인해보니 2번 변환하는것으로 확인되었음.

from collections import deque

def solution(begin, target, words):
    answer = 0
    popword = ''
    if target not in words:
        return 0
    else:
        deq = deque()
        deq.extend(words)
        while deq:
            popword = deq.popleft()
            if (True if [c1 == c2 for c1, c2 in zip(begin, popword)].count(False) == 1 else False) and (True if [c1 == c2 for c1, c2 in zip(target, popword)].count(False) >= 2 else False):
                answer += 1
                begin = popword
            elif (True if [c1 == c2 for c1, c2 in zip(begin, popword)].count(False) == 1 else False) and (True if [c1 == c2 for c1, c2 in zip(target, popword)].count(False) == 1 else False):
                return answer + 2



해결: if 문을 사용해서 주어지 begin과 target이 한개만 차이날경우에는 return 1을 해주는 코드를 넣음.



💡테스트 통과한 코드

begin: 처음 시작하는 단어
target: 만들어야하는 단어
words: 주어진 단어의 집합
answer: 최소 몇 단계의 과정을 거쳐 begin을 target으로 변환할 수 있는지 count하는 변수
popword: deq에서 꺼낸 단어를 담아두는 변수

  1. 만약 target이 words에 없다면 0 return.
  2. 만약 target과 begin이 하나만 다르다면 1 return.
  3. 그렇지 않다면 words의 단어를 다 deque에 넣고 deq이 존재할때까지 반복하면서 deq에서 단어를 하나씩 꺼내 popword 변수에 저장.
  4. 만약 popword단어와 begin단어가 1개 다르고 popword단어와 target단어가 2개 이상 다르다면 answer에 +1해주고 popword단어를 begin에 저장함.
  5. 만약 popword단어와 begin단어가 1개 다르고 popword단어와 target단어가 1개만 다르다면 answer+2를 return함.
from collections import deque

def solution(begin, target, words):
    answer = 0
    popword = ''
    if target not in words:
        return 0
    elif (True if [c1 == c2 for c1, c2 in zip(begin, target)].count(False) == 1 else False):
        return 1
    else:
        deq = deque()
        deq.extend(words)
        while deq:
            popword = deq.popleft()
            if (True if [c1 == c2 for c1, c2 in zip(begin, popword)].count(False) == 1 else False) and (True if [c1 == c2 for c1, c2 in zip(target, popword)].count(False) >= 2 else False):
                answer += 1
                begin = popword
            elif (True if [c1 == c2 for c1, c2 in zip(begin, popword)].count(False) == 1 else False) and (True if [c1 == c2 for c1, c2 in zip(target, popword)].count(False) == 1 else False):
                return answer + 2








🔗프로그래머스 - 단어 변환
https://programmers.co.kr/learn/courses/30/lessons/43163

profile
Cherish the moment :)

0개의 댓글