Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How to generate the power set of a given set, in Python?

"""
This implementation demonstrates how 
to generate the power set of an array 
of unique integers.

Example: 
For following array: [1, 2]
The power set is the set of all subsets of 
the array. 
So, output would be: [[], [1], [2], [1, 2]]

Let n be the size of the array.

Time complexity: O(n*2^n)
Space complexity: O(n*2^n)
"""


def powerset(array):
    # Empty set is part of power set
    subsets = [[]]
    for element in array:
        # Add every element to existing subsets
        for idx in range(len(subsets)):
            subset = subsets[idx]
            subsets.append(subset + [element])
    return subsets


print(powerset([1, 2]))  # [[], [1], [2], [1, 2]]
Comment

PREVIOUS NEXT
Code Example
Python :: sklearn plot confusion matrix 
Python :: dataframe copy 
Python :: how to read the first line in a file python 
Python :: pretty print pandas dataframe 
Python :: seaborn axis limits 
Python :: python multiply list by scalar 
Python :: timestamp to date python 
Python :: python check if a variable is an pandaDataframe 
Python :: jupyter notebook dark theme 
Python :: remove punctuation from string python 
Python :: python how to set the axis ranges in seaborn 
Python :: check string similarity python 
Python :: combination python 
Python :: pyspark distinct select 
Python :: exception get line number python 
Python :: eigenvectors python 
Python :: pen down python turtle 
Python :: open choose files from file explorer python 
Python :: how to install wxpython 
Python :: plotly set axes limits 
Python :: yield godot 
Python :: mongodb between two values 
Python :: How to Add a Title to Seaborn Plots 
Python :: discord.py set activity 
Python :: python check if port in use 
Python :: how to open file in BeautifulSoup 
Python :: image capture from camera python 
Python :: tkinter boilerplate 
Python :: order pandas dataframe by column values 
Python :: tkinter navigate pages 
ADD CONTENT
Topic
Content
Source link
Name
8+1 =