본문 바로가기

IT/Python

[백준] 15656, 15657번 N과 M[7, 8] [Python] - 중복 순열, 중복 조합

728x90

백준 문제 사이트

N과 M[7]

N과 M[8]

 

N과 M[3], N과 M[4]에서는 1~N까지 자연수로 이루어진 길이가 M인 수열을 출력했다면,

N과 M[7], N과 M[8]은 주어진 N개의 자연수로 이주어진 길이가 M인 수열을 출력하는 문제입니다. 

 

주어진 자연수를 정렬하고, 속도를 높이기 위해 문자로 변환 후,

중복 순열, 중복 조합의 경우를 구하고 출력하는 코드입니다.

 

product, combinations_with_replacement의 반환 값은 튜플 형태의 원소를 지니고 있어서, 

튜블 내 원소를 ' '$($공백$)$으로 이어 붙인 후

join 매소드로 줄바꿈으로 문자를 이어 붙였습니다.

 

N과 M[3], N과 M[4] 리뷰

https://savvy0402.tistory.com/6

https://savvy0402.tistory.com/7

 

N과 M[7]

import sys
from itertools import product
input = sys.stdin.readline

N, M = map(int, sys.stdin.readline().split())
li = sorted(map(int, sys.stdin.readline().split()))
pm = product(map(str, li), repeat=M)
print("\n".join(map(' '.join, pm)))

 

N과 M[8]

import sys
from itertools import combinations_with_replacement

N, M = map(int, sys.stdin.readline().split())
li = sorted(map(int, sys.stdin.readline().split()))
cm = combinations_with_replacement(map(str, li), M)
print("\n".join(map(' '.join, cm)))