
완전탐색문제이고, 문제를 보니 재귀로 풀어도 깊이 문제가 생기지 않을 것이라고 확신했기에 재귀로 풀었다.
따라서 for 문을 사용한 재귀를 사용하였고, 프로그래머스 문제의 특성상 global을 많이 사용하게 되어 머리가 잠시 삐로롱 되었지만, 금방 풀 수있었다.
초기에 필요한 변수들을 초기화해주고, solution에서도 초기화 과정을 거쳐준다.
그리고 aeiou에 매개변수로 string의 length인 number, 문자열, 찾고 있는 문자열로 3개의 매개변수를 이용했다.
aeiou를 for문으로 돌면서 모음사전인 vowel_dictionary에 추가 시키기로 했다.(지금보니 안해도 되는 과정이었다.)
그리고 index를 +1 해주면서, 몇 번째에 찾는 단어가 현재의 단어인지 확인하는 과정을 추가했다.
그리고 if문을 이용해 찾는 단어를 찾았으면, return하도록 설계했다.
이 때 한 번만 return하게 되면 재귀함수의 완전종료가 안되기 때문에, 확실히 종료하기 위해, for문 밖과 for문 안에도 find_word가 False일때만 작동하도록 만들었다.
if string+vowel[i] == find and not find_word:
find_word = True
return
재귀함수를 완전히 빠져나왔을때, 기록된 index값을 solution에서 반환하도록 하여 정답을 도출했다.
# 사전에 AEIOU 만을 사용하여 만들 수 있는 길이 5이하의 모든 단어가 수록
vowel = ['A', 'E', 'I', 'O', 'U']
index = 0
vowel_dictionary = []
find_word = False
def aeiou(number,string, find):
global vowel
global vowel_dictionary
global index
global find_word
# 단어길이가 5 이상이면 넘어갈 것.
if number >= 5:
return
# 단어길이가 5 미만이고 index 못찾았으면 진행
if not find_word:
for i in range(5):
if not find_word:
vowel_dictionary.append(string+vowel[i])
index += 1
if string+vowel[i] == find and not find_word:
find_word = True
return
aeiou(number+1, string+vowel[i], find)
return
def solution(word):
global vowel
global vowel_dictionary
global index
global find_word
index = 0
vowel_dictionary = []
find_word = False
aeiou(0,'', word)
return index
def solution(word):
answer = 0
for i, n in enumerate(word):
answer += (5 ** (5 - i) - 1) / (5 - 1) * "AEIOU".index(n) + 1
return answer
아래는 5중 for문 방법!
def solution(word):
answer = 0
alpha = ["A","E","I","O","U",""]
ans = []
for i in alpha:
for j in alpha:
for k in alpha:
for l in alpha:
for m in alpha:
w = i+j+k+l+m
if w not in ans: ans.append(w)
ans.sort()
answer = ans.index(word)
return answer
아니... 인간승리인 코드도 봤지만, 그건 차마 들고오지 못했다 ㄷㄷㄷ