A set of n elements has 2 to the power n subsets. Your program lists all of them in a fixed order: first the empty set, then the subsets with one element, then with two, and so on.
What to build
A program that prints the power set of a list of distinct elements.
Requirements
- Read one line of distinct words; the words are the elements of the set.
- Print every subset on its own line, written with braces and
,between elements, such as{a, c}; the empty set is{}. - Order the subsets by size, and subsets of the same size in the order given by choosing the elements in input order (the order of itertools.combinations).
- Finish with the line
N subsets.
Input
One line of 1 to 6 distinct words.
Output
The subsets, then the count.
Constraints
1 ≤ n ≤ 6.
Example
Input:
a b
Output:
{}
{a}
{b}
{a, b}
4 subsets
Why it works
Every element is either in a subset or out of it, so there are 2 to the power n subsets. Listing them by size with combinations visits each exactly once, and the last line shows the count agrees with the formula.
Examples
a b
{}
{a}
{b}
{a, b}
4 subsets
x y z
{}
{x}
{y}
{z}
{x, y}
{x, z}
{y, z}
{x, y, z}
8 subsets
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
itertools.combinations(items, size) lists the subsets of a given size in the input order.
Hint 2
Loop size from 0 to n and print each subset as {a, b}; the empty set is {}.
Hint 3
The number of subsets is 2**n; print it as the last line.
Solution
Show one correct solution (try it yourself first)
from itertools import combinations
items = input().split()
count = 0
for size in range(len(items) + 1):
for c in combinations(items, size):
print("{" + ", ".join(c) + "}")
count += 1
print(count, "subsets")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step