[알고리즘] 프로그래머스 모음사전 파이썬

SCY·2023년 9월 12일
0
post-thumbnail

[프로그래머스] LEVEL2 모음사전

🌱 문제

🌱 나의 풀이

나는 스택을 이용해 문제를 풀었다.
빈 스택으로 시작해서 하나씩 늘려주다가 word와 일치하는 순간 해당 answer를 반환했다.

내가 찾은 규칙은 다음과 같았다.

  • 스택의 top에 위치한 알파벳을 빼고 다음 알파벳 삽입
  • 스택의 top에 위치한 알파벳이 U라면 U 모두 + 바로 전까지 빼고 다음 알파벳 삽입

예시 ) AUUUO
1번 규칙 적용, AUUUO -> AUUUU
2번 규칙 적용, AUUUU -> AUUU -> AUU -> AU -> A -> [ ] -> E

def solution(word):
    answer = 0
    stack = []
    alp = ['A', 'E', 'I', 'O', 'U']
    
    while word != ''.join(stack):
        if len(stack) != 5:
            stack.append(alp[0])
        else:
            l = stack.pop()
            while l == alp[-1]:
                l = stack.pop()
            stack.append(alp[alp.index(l) + 1])
        answer += 1
        
    return answer

굳이 리스트를 생성하지 않고 문자열 사용해도 됐었다.

def solution(word):
    answer = 0
    stack = []
    while word != ''.join(stack):
        if len(stack) != 5:
            stack.append('A')
        else:
            p = stack.pop()
            while p == 'U':
                p = stack.pop()
            stack.append("AEIOU"["AEIOU".index(p) + 1])
        answer += 1
    return answer

🌱 다른 풀이

from itertools import product

solution = lambda word: sorted(["".join(c) for i in range(5) for c in product("AEIOU", repeat=i+1)]).index(word) + 1

문자열의 길이가 길지 않으니 product로 모든 경우의 수 탐색. 문자열도 sort가 된다.
한 문장 구현 멋지다.

def solution(word):
    answer = 0
    for i, n in enumerate(word):
        answer += (5 ** (5 - i) - 1) / (5 - 1) * "AEIOU".index(n) + 1
    return answer

이건 규칙을 이용한 풀이.

🌱 얻어가기

순열 permutations

from itertools import permutations

조합 combinations

from itertools import combinations

중복 순열 product

from itertools import product

중복 조합 combinations_with_replacement

from itertools import combinations_with_replacement

profile
성장 중독 | 서버, 데이터, 정보 보안을 공부합니다.

0개의 댓글