CONN-P4

Yes-or-no rules

Practice 4 of 4Connectivity13 tests

The problem

A planner must answer n yes-or-no questions, numbered 1 to n. Each rule is a pair (a, b) of two conditions, and at least one of the two must hold. The number k stands for “question k is answered yes”, and −k for “question k is answered no”. Return a list of n values: True for yes and False for no, question k at position k − 1. If no list of answers keeps every rule, return None.

rules = [(1, 2), (-1, 3), (-2, -3), (1, -2)]
two_sat(3, rules)              # [True, False, True]
two_sat(3, rules + [(-1, 2)])  # None

The rule (-1, 3) reads: question 1 is no, or question 3 is yes (or both). A rule may name the same condition twice, (2, 2), which means question 2 must be yes. When several lists keep every rule, any of them is accepted: the tests check your list against every rule.

Limits

  • Up to 50,000 questions and 100,000 rules.
  • Trying every list of answers is far too slow (2⁴⁰ lists for 40 questions). The implication graph can hold a path 100,000 vertices long. The big tests have 4 seconds each.

Builds on CONN-4 2-SAT.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

13 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2No answerNot run
3A rule with one condition twiceNot run
4Forced both waysNot run
5Always trueNot run
6No rulesNot run
7Yes is the wrong first guessNot run
8A chain that forces everythingNot run
940 questionsNot run
1050,000 questions, 100,000 rulesNot run
11A forced chain of 50,000Not run
12A chain of 50,000 that closesNot run
13A chain that forbids the lastNot run