SymPy | Subset.ksubsets() in Python

SymPy | Subset.ksubsets() in Python

In SymPy, the Subset class provides methods to work with subsets. The ksubsets() method of the Subset class is used to generate all the possible k-sized subsets of a given set.

Let's look at how to use the ksubsets() method:

Syntax:

Subset.ksubsets(S, k) 
  • S is the input set.
  • k is the size of the subsets you want to generate.

The method returns an iterator over k-sized subsets of S.

Example:

from sympy import * from sympy.combinatorics.subset import Subset # Define the set S = {1, 2, 3, 4} # Generate all 2-sized subsets of S k_subsets = list(Subset.ksubsets(S, 2)) # Print the results for subset in k_subsets: print(subset) 

This will produce the output:

{1, 2} {1, 3} {1, 4} {2, 3} {2, 4} {3, 4} 

These are all the 2-sized subsets of the set {1, 2, 3, 4}.

You can vary the value of k to get subsets of different sizes. Remember to ensure that k is not greater than the size of the set S, or you'll get an empty result.


More Tags

canoe image-editing historian xsd url-routing undo php-5.5 wkhtmltoimage uri git-fetch

More Programming Guides

Other Guides

More Programming Examples