Python - K length Combinations from given characters


K length combinations from given characters mean the combinations of characters that we can create with the given characters, which are exactly of length k. In this article, we will explore several methods to achieve this, like recursion, map and lambda function, itertools library, etc. While recursion and lambda functions are custom functions, the itertools provide the in-built method to generate the combinations.

Using Recursion

Recursion is one of the traditional programming techniques. In this technique, we try to break a large problem into smaller chunks of problems, and our motive is to solve the smaller problems to solve the larger problem ultimately. The recursion approach has a base case; we need to perform the recursion until we reach the recursion base case.

Example

In the following example, we created a function named generate_combinations, which takes the character and the length of the desired sequence. Under the function, we first made an empty list that holds our answer. Next, within that function, we have created another function named generate_helper which will append the combinations with lengths equal to k and is generated from the characters we passed to the function. We returned the list. To test the function, we created a list of characters named characters called the generate_combinations function and printed the result.

def generate_combinations(characters, k):
    combinations_list = []

    def generate_helper(current_combination, remaining_characters):
        if len(current_combination) == k:
            combinations_list.append(current_combination)
            return

        for char in remaining_characters:
            generate_helper(current_combination + char, remaining_characters)

    generate_helper('', characters)
    return combinations_list

characters = ['A', 'B', 'C', 'D', 'E']
k = 2

result = generate_combinations(characters, k)
print(result)

Output

['AA', 'AB', 'AC', 'AD', 'AE', 'BA', 'BB', 'BC', 'BD', 'BE', 'CA', 'CB', 'CC', 'CD', 'CE', 'DA', 'DB', 'DC', 'DD', 'DE', 'EA', 'EB', 'EC', 'ED', 'EE']

Using itertools Library To Generate K Length Combination

The itertools library in Python is a powerful tool that provides functions that can efficiently combine iterable objects. The library is available by default; hence, we do not need to install the library separately. The advantage of using the library is that it is memory efficient. Hence we should use this library while dealing with large data where memory efficiency and performance are important.

Example

In the following code, we first imported the product module from the itertools library of Python. Next, we created a function named generate_combinations which takes the sequence of characters and the length of the sequence we want to build. Under this function, we used the product method to create a list of possible combinations. Since the combinations are tuples, we used the join method of String to extract String from the list.

from itertools import product

def generate_combinations(characters, k):
    combinations_list = list(product(characters, repeat=k))
    combinations_strings = [''.join(comb) for comb in combinations_list]
    return combinations_strings

characters = ['A','B','C','D','E']
k = 2

result = generate_combinations(characters, k)
print(result)

Output

['AA', 'AB', 'AC', 'AD', 'AE', 'BA', 'BB', 'BC', 'BD', 'BE', 'CA', 'CB', 'CC', 'CD', 'CE', 'DA', 'DB', 'DC', 'DD', 'DE', 'EA', 'EB', 'EC', 'ED', 'EE']

Using Map Lambda Function

A lambda function is a convenient way to define a function without defining the name of the function. The function is useful when we want a quick operation, but we are sure it will only be used in the program. Hence it's a good practice to create a lambda function when you are sure that you don't need the reusability of the code and the logic is small enough.

On the other hand, Map applies any function to all the elements of iterable objects. It takes two parameters: the name of the function and the iterable object. For our use case, we can use the product method to generate all the combinations and use the map and lambda function to create a String out of the combinations.

Example

In the following code, we used the “product” method of the itertools Module. We created the generate_combinations function, which takes the list of characters and the length k as the arguments. Under the function, we used the product method to generate all the combinations. We passed the sequence and k-length of the sequences of our output. Next, we combined map and lambda functions to convert them into a String sequence. We finally returned the resulting list.

from itertools import product

def generate_combinations(characters, k):
    combinations_list = list(product(characters, repeat=k))
    combinations_strings = list(map(lambda comb: ''.join(comb), combinations_list))
    return combinations_strings

characters = ['P','Q','R','S','T']
k = 2

result = generate_combinations(characters, k)
print(result)

Output

['PP', 'PQ', 'PR', 'PS', 'PT', 'QP', 'QQ', 'QR', 'QS', 'QT', 'RP', 'RQ', 'RR', 'RS', 'RT', 'SP', 'SQ', 'SR', 'SS', 'ST', 'TP', 'TQ', 'TR', 'TS', 'TT']

Conclusion

In this article, we understood how to generate K length Combinations from given characters. We can create our logic to perform the same. Otherwise, Python also provides us with multiple libraries to achieve this. We can use the recursion technique, which aims to solve a smaller chunk of the problem. Next, we can use the ‘product’ method of the itertools library. We can also combine the lambda function and the map method with the product method for convenience.

Updated on: 18-Jul-2023

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements