2023. 8. 13. 23:03ㆍHackerRank-Python
itertools.combinations() | HackerRank
Print all the combinations of a string using itertools.
www.hackerrank.com
문제
Task
You are given a string S.
Your task is to print all possible combinations, up to size k, of the string in lexicographic sorted order.
Input Format
A single line containing the string S and integer value k separated by a space.
Output Format
Print the different combinations of string S on separate lines.
=> S와 k를 줄건데 S에 대해 조합들을 구하라. 조합의 길이는 최대k
코드
from itertools import combinations
S, k = input().split()
for i in range(int(k)):
for j in combinations(sorted(S), i+1):
print(''.join(j))
노트
from itertools import combinations
S, k = input().split()
print(S, k)
for i in range(int(k)):
for j in combinations(S, i+1):
print(j)
print(type(j))
print(''.join(j))
print(type(''.join(j)))
OUTPUT
HACK 2
('H',)
<class 'tuple'>
H
<class 'str'>
('A',)
<class 'tuple'>
A
<class 'str'>
('C',)
<class 'tuple'>
C
<class 'str'>
('K',)
<class 'tuple'>
K
<class 'str'>
('H', 'A')
<class 'tuple'>
HA
<class 'str'>
('H', 'C')
<class 'tuple'>
HC
<class 'str'>
('H', 'K')
<class 'tuple'>
HK
<class 'str'>
('A', 'C')
<class 'tuple'>
AC
<class 'str'>
('A', 'K')
<class 'tuple'>
AK
<class 'str'>
('C', 'K')
<class 'tuple'>
CK
<class 'str'>
- ''.join()에 튜플을 넣어도 알아서 해줌
for i in range(int(k)):
for j in combinations(sorted(S), i+1):
print(''.join(j))
- combinations()함수는 값들을 튜플로 리턴해줌
- 리턴 값들을 j에 저장하고, 문자열로 바꿔 출력하는 코드
두 번째 시도
from itertools import combinations
S, k = input().split()
for i in range(int(k)):
for j in list(combinations(sorted(list(S)), i+1)):
print(''.join(j))
- 발전이 없나..?
세 번째 시도
from itertools import combinations
S, k = input().split(" ")
k = int(k)
for i in range(k):
print('\n'.join((''.join(j) for j in combinations(sorted(S), i+1))))
참조
https://github.com/anarayanan86/Hackerrank/blob/master/Python/Itertools/itertools.combinations().py
<Hackerrank 문제풀이: 파이썬> itertools.combinations()
문제의 요구에 따르면 간단하게 풀 수 있는 조합 문제였다. from itertools import combinations S, num = input().split() list_S = list(S) for i in range(1, int(num)+1): for j in sorted(list(combinations(''.join(sorted(S)), i))): print(''.
hwan-hobby.tistory.com
'HackerRank-Python' 카테고리의 다른 글
Prepare > Python > Collections > collections.Counter() (0) | 2023.08.15 |
---|---|
Prepare > Python > Itertools > itertools.combinations_with_replacement() (0) | 2023.08.14 |
Prepare> Python > Itertools > itertools.permutations() (0) | 2023.08.05 |
Prepare > Python > Itertools > itertools.product() (0) | 2023.07.29 |
Prepare > Python > Sets > Check Strict Superset (0) | 2023.07.28 |