Logical Inference Engine: TRUE, FALSE, or Undetermined
Trees & GraphsModel answerLast updated
Build a function that classifies propositions as definitely true, definitely false, or undetermined given a set of facts and implication rules.
Background
Many automated systems — from diagnostic tools to configuration validators — need to reason about what must be true, what must be false, and what simply cannot be settled from the available evidence.
You are given a knowledge base made up of two components:
- Facts: propositions that are unconditionally known. A fact written as
"X"means variableXis true. A fact written as"!X"means variableXis false. - Rules: one-directional implications of the form
"P -> Q". This means: wheneverPholds,Qmust also hold. Rules carry their contrapositive for free — ifQis false, thenPmust also be false.
Both P and Q in a rule can be either a plain variable or a negated variable (e.g., "!A -> B" or "A -> !B").
Given these two components, your task is to evaluate a list of query variables and classify each one:
"TRUE"— the variable must be true in every consistent interpretation of the knowledge base."FALSE"— the variable must be false in every consistent interpretation."CANNOT_DETERMINE"— some consistent interpretations make it true and others make it false.
You may assume the knowledge base contains no contradictions.
Function Signature
def classify_propositions(
facts: list[str],
rules: list[str],
queries: list[str]
) -> list[str]:
pass
Input and Output
facts: strings of the form"X"or"!X".rules: strings of the form"X -> Y"where each side is a plain or negated variable.queries: plain variable names (no!prefix).- Returns a list of
"TRUE","FALSE", or"CANNOT_DETERMINE"in the same order asqueries.
Constraints
1 <= len(facts) <= 2000 <= len(rules) <= 5001 <= len(queries) <= 200- Variable names are alphanumeric, between 1 and 20 characters.
- The knowledge base is guaranteed to be consistent.
Examples
Example 1
facts = ["SensorActive", "!DoorLocked"]
rules = [
"SensorActive -> AlarmArmed",
"AlarmArmed -> MonitoringOn",
"DoorLocked -> DeadBoltEngaged"
]
queries = ["AlarmArmed", "DeadBoltEngaged", "SensorActive", "DoorLocked"]
# Expected output: ["TRUE", "CANNOT_DETERMINE", "TRUE", "FALSE"]
SensorActive is a fact, so it is TRUE. Following the rule chain, AlarmArmed and MonitoringOn are also TRUE. DoorLocked is directly negated by the facts, so it is FALSE. The rule DoorLocked -> DeadBoltEngaged only fires when DoorLocked is true — since it is false, DeadBoltEngaged is neither forced true nor forced false: CANNOT_DETERMINE.
Example 2
facts = ["!SystemOnline"]
rules = [
"ServiceRunning -> SystemOnline"
]
queries = ["ServiceRunning"]
# Expected output: ["FALSE"]
The contrapositive of ServiceRunning -> SystemOnline is !SystemOnline -> !ServiceRunning. Since SystemOnline is false, that fires and forces ServiceRunning to be false.
What is expected
Write the full function. Explain your algorithm, handle both forward inference and contrapositive propagation, and discuss complexity and any edge cases worth noting.
Hints
Hint 1
Model each literal (both X and !X) as a node in a directed graph. For every rule P -> Q, add two edges: one for the implication and one for its contrapositive (!Q -> !P). A clean way to encode this is to give variable i the ID 2i for its positive literal and 2i+1 for its negation, so flipping a literal is just XOR with 1.
Hint 2
Start by propagating all known facts through the implication graph via DFS or BFS. Every reachable literal is forced true in every model. This handles the straightforward cases — but it is not sufficient on its own.
Hint 3
Forward reachability misses cases where a variable is forced by contradiction rather than by a direct chain from the facts. To catch these, test each query by temporarily assuming its negation and propagating. If that assumption leads to a conflict (a literal and its negation both become true), then the assumption is impossible and the original variable must be TRUE. Apply the same test in the oth…
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a 2-SAT entailment problem. Each fact is a unit clause and each rule P -> Q is a two-literal clause (¬P ∨ Q). The goal is not to find one satisfying assignment, but to determine what every satisfying assignment must agree on.
Representing literals
Assign each distinct variable an integer index starting from 0. Encode the positive literal of variable i as 2i and its negation as 2i + 1. With this scheme, toggling a literal is always id ^ 1 — negation of a negation cancels automatically, and no separate lookup table is needed.
Building the implication graph
For every rule P -> Q, add:
- A forward edge
P → Q - A contrapositive edge
¬Q → ¬P
Each fact L seeds the set of known-true literals directly.
Phase 1 — Forward closure from the facts
Run a DFS/BFS starting from all fact literals. Every reachable literal is forced true in every valid model — call this set base. If the query variable X lands in base, the answer is TRUE. If ¬X lands in base, the answer is FALSE.
Phase 2 — Refutation testing
Forward closure is not complete. Consider the rules A -> B and A -> !B with no facts. Neither ¬A nor anything about A is reachable from an empty starting set, yet A must be false (assuming it leads to a contradiction). Forward reachability alone would return CANNOT_DETERMINE incorrectly.
The fix: for each query variable X, test whether assuming ¬X is consistent with base.
- Propagate
¬Xthrough the implication graph on top ofbase. - If any literal
Lis reached such that¬Lis already inbaseor is also reached, the assumption¬Xis contradictory — meaningXmust beTRUE.
Repeat with the assumption X to check for FALSE. If neither assumption produces a contradiction, the answer is CANNOT_DETERMINE.
Why this is correct
X is TRUE exactly when premises ∧ ¬X is unsatisfiable, and FALSE exactly when premises ∧ X is unsatisfiable. The propagation above decides this precisely for 2-SAT formulas: a conflict-free, implication-closed partial assignment always extends to a full model (a standard result from 2-SAT theory), so the absence of a detected conflict is sufficient to confirm consistency.
Complexity
Let V = number of variables, R = number of rules, Q = number of queries.
| Step | Time |
|---|---|
| Graph construction | O(R + V) |
| Initial closure | O(V + R) |
| Per query (two DFS runs) | O(V + R) |
| Overall | O((V + R) · Q) |
With the given limits this is roughly 700 × 200 ≈ 140,000 operations — trivially fast.
Space is O(V + R) for the graph.
Edge cases
- Unknown variable (appears in no fact or rule): nothing is reachable in either direction; result is
CANNOT_DETERMINE. - Variable that is a direct fact: answered immediately from
base, no DFS needed. - Negated literals on rule sides (
"!A -> !B"): the parser strips leading!characters and XORs accordingly; the contrapositive logic is identical. - Rules that force a variable without any supporting fact (
A -> B,A -> !B): the refutation test catches this — assumingAreaches bothBand¬B. - Cycles (
A -> B -> A): the DFS visited-set handles these safely.
Solution
from collections import defaultdict
def classify_propositions(
facts: list[str],
rules: list[str],
queries: list[str]
) -> list[str]:
ids: dict[str, int] = {}
def lit(token: str) -> int:
"""Convert a token like 'A', '!A', '!!A' to an integer literal ID."""
token = token.strip()
neg = 0
while token.startswith("!"):
neg ^= 1
token = token[1:].strip()
if token not in ids:
ids[token] = len(ids)
return 2 * ids[token] + neg # flip negation with ^ 1
# Build implication graph
adj: dict[int, list[int]] = defaultdict(list)
for rule in rules:
left, right = rule.split("->")
p, q = lit(left), lit(right)
adj[p].append(q) # P -> Q
adj[q ^ 1].append(p ^ 1) # !Q -> !P (contrapositive)
def propagate(starts: list[int], base: set[int]) -> set[int]:
"""Return all literals reachable from starts, excluding those in base."""
reached: set[int] = set()
stack = [s for s in starts if s not in base]
reached.update(stack)
while stack:
u = stack.pop()
for v in adj.get(u, ()):
if v not in base and v not in reached:
reached.add(v)
stack.append(v)
return reached
# Phase 1: forward closure from all facts
base = propagate([lit(f) for f in facts], set())
def is_contradictory(assumption: int) -> bool:
"""True if adding this literal to the knowledge base causes a conflict."""
# Already known false — immediate contradiction
if assumption ^ 1 in base:
return True
# Already known true — assumption is vacuously consistent, not contradictory
if assumption in base:
return False
reached = propagate([assumption], base)
# Conflict if any reached literal's negation is in base or also reached
return any((l ^ 1) in base or (l ^ 1) in reached for l in reached)
results: list[str] = []
for q in queries:
x = lit(q)
if x in base:
results.append("TRUE")
elif x ^ 1 in base:
results.append("FALSE")
elif is_contradictory(x ^ 1):
# Assuming !X leads to contradiction, so X must be TRUE
results.append("TRUE")
elif is_contradictory(x):
# Assuming X leads to contradiction, so X must be FALSE
results.append("FALSE")
else:
results.append("CANNOT_DETERMINE")
return results
Common mistakes
- Skipping the contrapositive edges. Without
¬Q → ¬P, Example 2 fails entirely. - Stopping at forward reachability. This is the most frequent gap. It misses variables forced by contradiction (the
A -> B,A -> !Bpattern). Always implement the refutation test. - Conflating reachability with truth. A literal being reachable from a false fact means nothing — propagation must start only from known-true literals.
Follow-up: detecting an inconsistent knowledge base
After computing base, check whether any literal L and its negation L ^ 1 are both present. For a deeper check, add a unit-propagation edge ¬L → L for every fact L and run Kosaraju or Tarjan SCC. The premises are inconsistent if and only if some variable X and ¬X share a strongly connected component.