 # Python program to get all subsets of given size of a set

## Python program to get all subsets of given size of a set

Given a set, write a Python program to generate all possible subset of size n of given set within a list.
Examples:

```Input : {1, 2, 3}, n = 2
Output : [{1, 2}, {1, 3}, {2, 3}]

Input : {1, 2, 3, 4}, n = 3
Output : [{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}]```

We have already discussed the same problem using the Naive approach in this article. This article focuses on the Pythonic approaches to Print all subsets of a given size of a set.

Python has itertools.combinations(iterable, n) which Return n length subsequences of elements from the input iterable. This can be used to Print all subsets of a given size of a set. Now, we have various alternatives to use this function.

Code #1 :
Simply pass the set as iterable and the size as arguments in the itertools.combinations() to directly fetch the combination list.

 `# Python Program to Print` `# all subsets of given size of a set` `import` `itertools` `def` `findsubsets(s, n):` `    ``return` `list``(itertools.combinations(s, n))` `# Driver Code` `s ``=` `{``1``, ``2``, ``3``}` `n ``=` `2` `print``(findsubsets(s, n))`

Output:

`[(1, 2), (1, 3), (2, 3)]`

Code #2 :
We can also use an alternative to the above-discussed method which is mapping set to itertools.combinations() function.

 `# Python Program to Print` `# all subsets of given size of a set` `import` `itertools` `from` `itertools ``import` `combinations, chain` `def` `findsubsets(s, n):` `    ``return` `list``(``map``(``set``, itertools.combinations(s, n)))` `    ` `# Driver Code` `s ``=` `{``1``, ``2``, ``3``}` `n ``=` `2` `print``(findsubsets(s, n))`

Output:

`[{1, 2}, {1, 3}, {2, 3}]`

Code #3 :
Another method is to use for loop in itertools.combinations() function and append the combination sets to the list.

 `# Python Program to Print` `# all subsets of given size of a set` `import` `itertools` `# def findsubsets(s, n):` `def` `findsubsets(s, n):` `    ``return` `[``set``(i) ``for` `i ``in` `itertools.combinations(s, n)]` `    ` `# Driver Code` `s ``=` `{``1``, ``2``, ``3``, ``4``}` `n ``=` `3` `print``(findsubsets(s, n))`

Output:

`[{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}]`

Code #4:

Many a time when this question is asked in interviews, it’s better to answer without using any module. So, here is the solution that does not use itertools module:

 `def` `subsets(numbers):` `    ``if` `numbers ``=``=` `[]:` `        ``return` `[[]]` `    ``x ``=` `subsets(numbers[``1``:])` `    ``return` `x ``+` `[[numbers[``0``]] ``+` `y ``for` `y ``in` `x]` `# wrapper function` `def` `subsets_of_given_size(numbers, n):` `    ``return` `[x ``for` `x ``in` `subsets(numbers) ``if` `len``(x)``=``=``n]` `if` `__name__ ``=``=` `'__main__'``:` `    ``numbers ``=` `[``1``, ``2``, ``3``, ``4``]` `    ``n ``=` `3` `    ``print``(subsets_of_given_size(numbers, n))`

Output:

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

Last Updated on March 1, 2022 by admin

## Python Functools – lru_cache()Python Functools – lru_cache()

Python Functools – lru_cache() The functools module in Python deals with higher-order functions, that is, functions operating on(taking as arguments) or returning functions and other such callable objects. The functools module provides a wide array of methods such as cached_property(func), cmp_to_key(func), lru_cache(func), wraps(func), etc.

## How to save a Python Dictionary to a CSV File?How to save a Python Dictionary to a CSV File?

How to save a Python Dictionary to a CSV File? CSV (comma-separated values) files are one of the easiest ways to transfer data in form of string especially to any spreadsheet program like Microsoft Excel or Google spreadsheet. In this article,

## Python String isspace() MethodPython String isspace() Method

Python String isspace() Method Python String isspace() is a built-in method used for string handling. The isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument

## Python bytearray() functionPython bytearray() function

Python | bytearray() function bytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256. Syntax:   bytearray(source, encoding, errors) Parameters: source[optional]: Initializes the

## get_attribute() element method – Selenium Pythonget_attribute() element method – Selenium Python

get_attribute() element method – Selenium Python get_attribute() element method – Selenium Python Difficulty Level : Basic Last Updated : 27 Apr, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write

## How to open and close a file in PythonHow to open and close a file in Python

How to open and close a file in Python There might rise a situation where one needs to interact with external files with Python.Python provides inbuilt functions for creating, writing and reading files. in this article, we will be discussing how

## sys.stdout.write in Pythonsys.stdout.write in Python

sys.stdout.write in Python This is a built-in Python module that contains parameters specific to the system i.e. it contains variables and methods that interact with the interpreter and are also governed by it. sys.stdout A built-in file object that is

## IntegerField – Django ModelsIntegerField – Django Models

IntegerField – Django Models IntegerField is a integer number represented in Python by a int instance. This field is generally used to store integer numbers in the database. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise. It supports values from