Log In Sign Up
Day 54

Day 54: Power Set

54/60 Days

Day 54: Power Set #

Welcome to Day 54 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore the Power Set problem, a classic combinatorial problem that has applications in various areas of computer science and mathematics.

What is a Power Set? #

The power set of a set S is the set of all subsets of S, including the empty set and S itself. For a set with n elements, its power set contains 2^n elements.

For example, for the set {1, 2, 3}, its power set is: {{}, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}}

Approaches to Generate Power Set #

We’ll explore three different approaches to generate the power set:

  1. Iterative approach using bit manipulation
  2. Recursive approach
  3. Iterative approach using itertools

1. Iterative Approach Using Bit Manipulation #

This approach uses the bit manipulation techniques we learned yesterday. We represent each subset as a binary number where each bit represents the presence (1) or absence (0) of an element.

 1def power_set_bit(s):
 2    n = len(s)
 3    power_set = []
 4    for i in range(1 << n):
 5        subset = [s[j] for j in range(n) if (i & (1 << j))]
 6        power_set.append( …