Skip to content

Basic Power Set Generation

the ice cream flavors example. It shows how to generate all possible

Code

#!/usr/bin/env python3
"""
Filename: basic_power_sets.py
Description: Basic Power Set Generation

This script demonstrates the fundamental concept of power sets using
the ice cream flavors example. It shows how to generate all possible
subsets of a given set and verifies the cardinality formula.
"""

from itertools import combinations

def power_set(s):
    """Generate all subsets of a set"""
    s = list(s)  # Convert to list for indexing
    power_set_list = []

    # Generate all possible combinations of all lengths
    for r in range(len(s) + 1):
        for combo in combinations(s, r):
            power_set_list.append(set(combo))

    return power_set_list

def main():
    # Ice cream flavors example
    flavors = {'Chocolate', 'Vanilla', 'Mocha'}
    power_flavors = power_set(flavors)

    print(f"Original set of flavors: {flavors}")
    print(f"Power set P(flavors) - all possible ice cream combinations:")

    for i, subset in enumerate(power_flavors):
        if len(subset) == 0:
            print(f"  {i}: {subset} (no ice cream)")
        else:
            print(f"  {i}: {subset}")

    print(f"\nCardinality verification:")
    print(f"  |S| = {len(flavors)} flavors")
    print(f"  |P(S)| = {len(power_flavors)} total combinations")
    print(f"  Formula: 2^|S| = 2^{len(flavors)} = {2**len(flavors)}")
    print(f"  Formula verified: {len(power_flavors) == 2**len(flavors)}")

if __name__ == "__main__":
    main()

How to Use

  1. Copy the code above
  2. Save it as a .py file (e.g., basic_power_sets.py)
  3. Run it with: python basic_power_sets.py

Part of CS 5001/5002 - Strings, Sequences & Sets materials