Модуль itertools.combinations () в Python для печати всех возможных комбинаций

Опубликовано: 18 Января, 2022

Учитывая массив размера n, сгенерируйте и распечатайте все возможные комбинации r элементов в массиве.

Примеры:

Ввод: arr [] = [1, 2, 3, 4],  
            г = 2
Вывод: [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

Эта проблема имеет существующее рекурсивное решение, пожалуйста, обратитесь к Распечатайте все возможные комбинации элементов r в заданном массиве размера n ссылка. Мы решим эту проблему в Python с помощью модуля itertools.combinations ().

Что делает itertools.combinations ()?

Он возвращает r подпоследовательностей элементов из итерируемого ввода. Комбинации выводятся в порядке лексикографической сортировки. Итак, если входной итерабельный объект отсортирован, комбинационные кортежи будут создаваться в отсортированном порядке.

  • itertools.combinations(iterable, r) :
    It return r-length tuples in sorted order with no repeated elements. For Example, combinations(‘ABCD’, 2) ==> [AB, AC, AD, BC, BD, CD].
  • itertools.combinations_with_replacement(iterable, r) :
    It return r-length tuples in sorted order with repeated elements. For Example, combinations_with_replacement(‘ABCD’, 2) ==> [AA, AB, AC, AD, BB, BC, BD, CC, CD, DD].
    # Function which returns subset or r length from n
    from itertools import combinations
      
    def rSubset(arr, r):
      
        # return list of all subsets of length r
        # to deal with duplicate subsets use 
        # set(list(combinations(arr, r)))
        return list(combinations(arr, r))
      
    # Driver Function
    if __name__ == "__main__":
        arr = [1, 2, 3, 4]
        r = 2
        print (rSubset(arr, r))

    Output:

    [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
    

    This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

     Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

    To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course