거누의 개발노트

파이썬 알고리즘 인터뷰 - 전화 번호 문자 조합 본문

코딩테스트

파이썬 알고리즘 인터뷰 - 전화 번호 문자 조합

Gogozzi 2022. 5. 19. 15:23
반응형

문제

2에서 9까지 숫자가 주어졌을 때 전화 번호로 조합 가능한 모든 문자를 출력하라.

입력

"23"

출력

['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']

작성한 코드

def letterCombinations(digits: str) -> List[str]:
    if digits == '': return []

    phone = [[],['a','b','c'],['d','e','f'],['g','h','i'],['j','k','l'],['m','n','o'],['p','q','r','s'],['t','u','v'],['w','x','y','z']]

    lst = [int(i) for i in digits]
    l = [phone[i-1] for i in lst]
    pro = list(itertools.product(*l))

    return [''.join(i) for i in pro]

Product 구조

def productExam(*args, repeat=1):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = [tuple(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

리트코드에서 확인

https://leetcode.com/problems/letter-combinations-of-a-phone-number/

 

Letter Combinations of a Phone Number - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

회고

collections 모듈에는 product라는 클래스가있는데 이 클래스는 두 개이상의 리스트의 모든 조합을 구하는 로직이다.

 

반응형
Comments