Generating Powerset of a String in Python

  • Share this:

Code introduction


This function takes a string s and returns the powerset of s, which is a collection of all possible subsets of s.


Technology Stack : Set, String

Code Type : Generate power set

Code Difficulty : Intermediate


                
                    
def get_powerset(s):
    def powerset(s):
        """
        Generates the powerset of a given set s.
        """
        # Convert string to set of characters
        elements = set(s)
        # Base case: empty set
        powerset_ = [[]]
        # Generate powersets
        for element in elements:
            powerset_ += [subset + [element] for subset in powerset_]
        return powerset_
    
    return powerset(s)                
              
Tags: