인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

Inflearn Community Q&A

dasomjang331274's profile image
dasomjang331274

asked

Introduction to Python Algorithm Problem Solving (Coding Test Preparation)

section7 알파코드 질문입니다.

Written on

·

141

0

아래와 같이 각 알파벳에 대응하는 숫자 i(0<i<27)가 10 미만인 경우와 10 이상인 경우를 나누어 코드를 짰는데요, 입력된 숫자코드를 리스트로 바꿀 경우 원소가 항상 10 미만이기 때문에 다음과 같은 코드가 작동할 것이라고 생각했는데 정답이 안 나오네요. 정답이 안 나오는 이유를 알 수 있을까요?

def dfs(L,P): 

     global cnt

     if L==n:

          cnt+=1

          print(res)

          for i in range(P):

               print(chr(65+res[i]),end="")

          print()

     else:

          for i in range(1,27): # 모든 알파벳의 경우 탐색

               if i<10:

                    if code[L]==i: #L번째 숫자가 i와 일치할 경우

                         res[P]==i

                         dfs(L+1,P+1)

               else: # if i>=10

                    if code[L]==i//10 and code[L+1]==i%10: #연속된 두개의 숫자가 i와 일치할 경우

                         res[P]=i

                         dfs(L+2,P+1) # code에서는 L+2부터 탐색을 하고, res의 P+1번째 숫자를 구함

if __name__=="__main__":

     code=[int(c) for c in input()]

     n=len(code)

     code.append(-1)

     res=[0]*n

     cnt=0

     dfs(0,0)

     print(cnt)

python코테 준비 같이 해요!

Answer 1

0

codingcamp님의 프로필 이미지
codingcamp
Instructor

안녕하세요^^ 단순실수인것 같습니다.

def dfs(L,P): 

     global cnt

     if L==n:

          cnt+=1

          print(res)

          for i in range(P):

               print(chr(65+res[i]),end="")  <--65가 아니라 64로 해야 정확한 알파벳이 나옵니다.

          print()

     else:

          for i in range(1,27): # 모든 알파벳의 경우 탐색

               if i<10:

                    if code[L]==i: #L번째 숫자가 i와 일치할 경우

                         res[P]==i  <--res[P]=i로 값을 넣어주어야 합니다. 

                         dfs(L+1,P+1)

               else: # if i>=10

                    if code[L]==i//10 and code[L+1]==i%10: #연속된 두개의 숫자가 i와 일치할 경우

                         res[P]=i

                         dfs(L+2,P+1) # code에서는 L+2부터 탐색을 하고, res의 P+1번째 숫자를 구함

if __name__=="__main__":

     code=[int(c) for c in input()]

     n=len(code)

     code.append(-1)

     res=[0]*n

     cnt=0

     dfs(0,0)

     print(cnt)

dasomjang331274's profile image
dasomjang331274

asked

Ask a question