Coding/Python

[python]리스트 순열, 조합

후__아 2024. 4. 18. 14:52

# tuple 형식으로 return

※ product(리스트, repeat=자리수)

중복O, 모든 조합

from itertools import product   # 중복순열

''.join(i) for i in list(product('ABC', repeat = 2))     # AA AB AC BA BB BC CA CB CC

 

※ permutations(리스트, repeat=자리수)

중복X, 순서O

from itertools import permutations   # 순열

permutations('ABC', 2)       # AB AC BA BC CA CB

 

※ combinations(리스트, repeat=자리수)

중복X, 순서X

from itertools import combinations    # 조합

combinations('ABC', 2)      # AB AC BC

 

# 프로그래머스 배열 만들기2
from itertools import product
def solution(l, r):
    cnt, r2 = 0, r
    while r2 > 1:
        r2 /= 10        # r값을 그대로 사용하면 바뀌므로! r2로 copy
        cnt += 1

    arr = list(map(int, [''.join(i) for i in list(product('05', repeat=cnt))]))
    arr = [x for x in arr if x>=l and x<=r]  # 조건문 list comprehension 어순 기억!
    return arr if arr else [-1]

 

# 순열, 조합 함수 만들기