A relation R(x, y) on a small domain can be written as a table of 0s and 1s, where row x and column y hold 1 when R(x, y) is true. Quantifier statements about R then become questions about rows and columns.
What to build
A program that decides four nested quantifier statements about a table.
Requirements
- Read n, then n lines with n values 0 or 1: the table M, where M[x][y] = 1 means R(x, y) is true.
- Print four lines, each
yesorno, for these statements in this order, with x and y ranging over the n rows and columns. - Line 1: for all x there exists y with R(x, y). Line 2: there exists y such that for all x R(x, y). Line 3: there exists x such that for all y R(x, y). Line 4: for all y there exists x with R(x, y).
Input
The first line has n; then n lines of n values.
Output
Four lines, yes or no.
Constraints
1 ≤ n ≤ 8.
Example
Input:
3
1 0 0
0 1 0
0 0 1
Output:
yes
no
no
yes
Why it works
Each statement is a pattern of all and any over the table. A row with a 1 in every column makes the third statement true, a column of ones makes the second true, and the first and fourth only need a 1 somewhere in each row or column. Swapping the quantifiers changes which pattern is tested, which is why the order matters.
Examples
3 1 0 0 0 1 0 0 0 1
yes no no yes
2 1 0 1 0
yes yes no no
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Row x of the table is R(x, 0), R(x, 1), and so on. all(any(row) for row in M) is "for all x there exists y".
Hint 2
For "there exists y for all x" test the columns: any(all(M[x][y] for x in range(n)) for y in range(n)).
Hint 3
The four statements differ only in which quantifier comes first and which variable is the row.
Solution
Show one correct solution (try it yourself first)
n = int(input()) M = [list(map(int, input().split())) for _ in range(n)] yes = lambda b: "yes" if b else "no" print(yes(all(any(M[x][y] for y in range(n)) for x in range(n)))) print(yes(any(all(M[x][y] for x in range(n)) for y in range(n)))) print(yes(any(all(M[x][y] for y in range(n)) for x in range(n)))) print(yes(all(any(M[x][y] for x in range(n)) for y in range(n))))
▶ Open this solution in the compiler, then press Visualize to watch it run step by step