Categories
Coding Computer Science Python

Solving Problem: Combinations

(Python)

You are given a string S.
Your task is to print all possible combinations, up to size, of the string in lexicographically sorted order.

A single line containing the string and integer value separated by a space.

0 < k <= len(S)


The string contains only UPPERCASE characters.

Print the different combinations of the string on separate lines.

HACK 2

Sample Output

A
C
H
K
AC
AH
AK
CH
CK
HK
combinations.py
Python
from itertools import combinations
# Input from user
inp = input().split()
S = inp[0]
k = int(inp[1])
li1 = []
# Create a list with combinations
for i in range(1, k+1):
li1.extend(list(combinations(S, i)))
# Sort the list lexicographically
for i in range(0, len(li1)):
li1[i] = str(''.join(sorted(list(li1[i]))))
li1 = sorted(li1, key=lambda s: (len(s), s.lower())) # sort the list alphabetically ascending
# print the string
for i in range(0, len(li1)):
print(li1[i])

itertools.combinations() | HackerRank