Binary Representation and Power Set Formula¶
and power sets, showing how each subset corresponds to a binary number
Code¶
#!/usr/bin/env python3
"""
Filename: binary_power_sets.py
Description: Binary Representation and Power Set Formula
This script demonstrates the connection between binary representation
and power sets, showing how each subset corresponds to a binary number
and verifying the 2^n formula across different set sizes.
"""
def binary_to_subset(binary_str, elements):
"""Convert a binary string to a subset based on element positions"""
subset = set()
for i, bit in enumerate(binary_str):
if bit == '1' and i < len(elements):
subset.add(elements[i])
return subset
def main():
# Binary representation connection with 3 elements
elements = ['C', 'V', 'M'] # Chocolate, Vanilla, Mocha (abbreviated)
n = len(elements)
print(f"Binary Representation Connection")
print(f"Elements: {elements}")
print(f"Each subset corresponds to a {n}-bit binary number:")
print()
for i in range(2**n): # 2^n possibilities
binary = format(i, f'0{n}b') # n-bit binary representation
subset = binary_to_subset(binary, elements)
print(f" {binary} -> {subset}")
print(f"\nTotal subsets: {2**n} = 2^{n}")
# Verify the formula with different sized sets
print(f"\nFormula Verification Across Different Set Sizes:")
print(f"{'Set Size':<10} {'Actual |P(S)|':<15} {'Expected 2^n':<15} {'Verified':<10}")
print("-" * 55)
for size in range(1, 6):
test_set = set(range(size)) # {0}, {0,1}, {0,1,2}, etc.
# Count all possible subsets
actual_count = 2 ** size # We know this mathematically
expected_count = 2 ** size
verified = actual_count == expected_count
print(f"{size:<10} {actual_count:<15} {expected_count:<15} {'YES' if verified else 'NO':<10}")
print(f"\nKey Insight: Every subset can be represented as a binary number!")
print(f" - Bit position i: include element i if bit = 1, exclude if bit = 0")
print(f" - This is why |P(S)| = 2^|S| for any finite set S")
if __name__ == "__main__":
main()
How to Use¶
- Copy the code above
- Save it as a
.pyfile (e.g.,binary_power_sets.py) - Run it with:
python binary_power_sets.py
Part of CS 5001/5002 - Strings, Sequences & Sets materials