A partition of a set U splits it into non-empty groups that do not overlap and together cover every element. Your program checks whether a family of sets is a partition of U, and names the first problem if it is not.
What to build
A program that decides whether k given sets form a partition of U.
Requirements
- Read the elements of U on one line, then k on the next line, then k lines, each holding the elements of one set. Every element of every set belongs to U.
- Go through the elements of U in the order given. If an element appears in two or more of the sets, print
overlap:and that element. - Otherwise, if some element of U appears in no set, print
missing:and the first such element in the order given. - Otherwise print
partition.
Input
Line 1: the elements of U. Line 2: k. Then k lines, each a non-empty set.
Output
One line.
Constraints
1 ≤ |U| ≤ 12; 1 ≤ k ≤ 6.
Example
Input:
1 2 3 4
2
1 2
3 4
Output:
partition
Why it works
A partition needs two things: the sets must not overlap, so each element is in at most one of them, and they must cover U, so each element is in at least one. Counting the sets that hold each element tests both conditions at once: the count must be exactly 1 for every element.
Examples
1 2 3 4 2 1 2 3 4
partition
1 2 3 4 2 1 2 2 3
overlap: 2
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Count in how many of the given sets each element of U appears.
Hint 2
Check the elements of U in input order. An element in two or more sets is an overlap; an element in none is missing.
Hint 3
Report an overlap before a missing element: look for overlaps first, over the whole universe, then for missing elements.
Solution
Show one correct solution (try it yourself first)
U = input().split()
k = int(input())
sets = [set(input().split()) for _ in range(k)]
answer = "partition"
for x in U:
if sum(x in s for s in sets) >= 2:
answer = "overlap: " + x
break
else:
for x in U:
if not any(x in s for s in sets):
answer = "missing: " + x
break
print(answer)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step