Computer >> Computer tutorials >  >> Programming >> Python

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


In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given two integers, we need to display the common divisors of two numbers

Here we are computing the minimum of the two numbers we take as input. A loop to calculate the divisors by computed by dividing each value from 1 to the minimum computed.

Each time the condition is evaluated to be true counter is incremented by one.

Now let’s observe the concept in the implementation below−

Example

# built-in module
import itertools
def findsubsets(str_, n):
   return list(itertools.combinations(s, n))
# Driver Code
str_ = {'t','u','t','o','r'}
n = 2
print(findsubsets(str_, n))

Output

[('u', 'r'), ('u', 'o'), ('u', 't'), ('r', 'o'), ('r', 't'), ('o',
't')]

Example

# using combinations function in itertools
from itertools import combinations
def findsubsets(str_, n):
   return list(map(set, itertools.combinations(s, n)))
str_ = {'t','u','t','o','r'}
n = 3
print(findsubsets(str_, n))

Output

[{'u', 'o', 'r'}, {'u', 'r', 't'}, {'u', 'o', 't'}, {'o', 'r', 't'}]

Example

# using combinations function in itertools and appending in a new list
def findsubsets(str_, n):
   return [set(i) for i in itertools.combinations(s, n)]
str_ = {'t','u','t','o','r'}
n = 3
print(findsubsets(str_, n))

Output

[{'u', 'o', 'r'}, {'u', 'r', 't'}, {'u', 'o', 't'}, {'o', 'r', 't'}]

All the variables are declared in the local scope and their references are seen in the figure above.

Conclusion

In this article, we have learned about python object comparison by using equality & the referencing operator(is).