How to get all combinations of K characters from a string (not contiguous) in Python

1 Answer

0 votes
from itertools import combinations

def k_combinations(s, k):
    return [''.join(c) for c in combinations(s, k)]


result = k_combinations("abcdefg", 4)

print(result)


'''
run:

['abcd', 'abce', 'abcf', 'abcg', 'abde', 'abdf', 'abdg', 'abef', 'abeg', 'abfg', 'acde', 'acdf', 'acdg', 'acef', 'aceg', 'acfg', 'adef', 'adeg', 'adfg', 'aefg', 'bcde', 'bcdf', 'bcdg', 'bcef', 'bceg', 'bcfg', 'bdef', 'bdeg', 'bdfg', 'befg', 'cdef', 'cdeg', 'cdfg', 'cefg', 'defg']

'''

 



answered Mar 8 by avibootz
...