Theory of Computation | Semester 4 Core Notes

Semester 4 - Page 3: Theory of Computation. 30 numbered topics, highlighted definitions, worked derivations, answered exam questions, three diagrams, comparison tables and three complete Python 3 recognizers. General common-core preparation, not an official syllabus or past-paper prediction. Epsilon denotes the empty string; notation varies across courses.

Choose the right claim: membership, language equivalence, recognizability, decidability and efficient computation are different questions. Run each Python block separately. These finite-input simulations illustrate the machine ideas; they are not universal proofs. Invalid alphabet symbols are rejected or reported as the program states.

Topic map

  1. Alphabet, strings and empty objects
  2. Language operations and powers
  3. DFA formal definition
  4. Worked suffix DFA and traces
  5. Dead states and extended transition
  6. NFA definition and acceptance
  7. Epsilon moves and closure
  8. Subset construction and equivalence
  9. Regular expressions and precedence
  10. Regex, automata and Arden equations
  11. Closure of regular languages
  12. DFA minimization and distinguishing suffixes
  13. Regular pumping lemma and quantifiers
  14. Myhill-Nerode and nonregularity
  15. Context-free grammars and derivation
  16. Parse trees, ambiguity and precedence
  17. Grammar simplification, CNF and GNF
  18. PDA and stack recognition
  19. PDA acceptance and determinism
  20. CFL closure and decision questions
  21. CFL pumping and the triple-count language
  22. Chomsky hierarchy
  23. Turing machine definition and configurations
  24. Machine variants and Church-Turing thesis
  25. Recognizers, deciders and complements
  26. Universal simulation and enumerators
  27. Undecidability and the halting contradiction
  28. Mapping reductions, PCP and Rice's theorem
  29. Complexity, P and NP
  30. Proof and revision checklist

1. Alphabet, strings and empty objects

An alphabet is a finite set of symbols; a string is a finite sequence of them. The empty string epsilon has length zero. The empty language contains no strings, while {epsilon} contains one.

Worked example: For Sigma={A,B}, AB is a string of length 2; epsilon is in Sigma star but not in the empty language.
Exam question: Is an empty language the same as the language containing the empty string?
Answer: No. Their cardinalities are zero and one respectively.

2. Language operations and powers

A language is a subset of Sigma star. Union collects members of either language; concatenation joins one string from each; Kleene star permits zero or more repetitions and always includes epsilon.

Worked example: If L={AB}, then L squared={ABAB}, and L star={epsilon,AB,ABAB,...}. Concatenation with the empty language gives the empty language.
Exam question: Does L star equal L plus?
Answer: L plus allows one or more factors. They can differ on epsilon; if epsilon is already in L, both include it.

3. DFA formal definition

A DFA is (Q,Sigma,delta,q0,F), with finite states Q, total transition function delta:Q x Sigma->Q, start q0 and accepting set F. Acceptance is determined after all input is consumed.

Worked example: A ticket recognizer records no useful suffix, suffix A, or suffix AB; the final suffix AB state is accepting.
Exam question: Can a DFA have two outgoing A transitions from one state?
Answer: No. Exactly one next state is defined per state and alphabet symbol.

4. Worked suffix DFA and traces

A suffix recognizer stores only enough recent history to decide the language. For strings over {A,B} ending in AB, three states suffice; acceptance in the middle of input is not final acceptance.

Worked example: q0: A->qA,B->q0; qA: A->qA,B->qAB; qAB: A->qA,B->q0. BAB ends qAB; ABA ends qA.
Exam question: Why does qAB on A go to qA rather than q0?
Answer: The last A may begin the next desired AB suffix.
start q0 --A--> qA --B--> [qAB accepts]
q0: B loops
qA: A loops
qAB: A -> qA; B -> q0
Complete transition diagram in text form. Only qAB accepts after the whole input.

DFA for strings ending in AB

def ends_ab(text):
    transition = {"q0": {"A": "qA", "B": "q0"},
                  "qA": {"A": "qA", "B": "qAB"},
                  "qAB": {"A": "qA", "B": "q0"}}
    state = "q0"
    trace = [state]
    for symbol in text:
        if symbol not in {"A", "B"}:
            raise ValueError("symbol outside alphabet")
        state = transition[state][symbol]
        trace.append(state)
    return state == "qAB", trace

for text in ["", "AB", "BAB", "ABA", "AAB"]:
    print(repr(text), ends_ab(text))
try:
    ends_ab("ABC")
except ValueError:
    print("invalid symbol rejected")

Checked output:

'' (False, ['q0'])
'AB' (True, ['q0', 'qA', 'qAB'])
'BAB' (True, ['q0', 'q0', 'qA', 'qAB'])
'ABA' (False, ['q0', 'qA', 'qAB', 'qA'])
'AAB' (True, ['q0', 'qA', 'qA', 'qAB'])
invalid symbol rejected

5. Dead states and extended transition

A dead or sink state loops on every alphabet symbol and cannot reach acceptance. The extended transition delta star processes a whole string, with delta star(q,epsilon)=q.

Worked example: A DFA requiring exactly two A symbols can send any extra A after the second to a sink. Empty input is accepted precisely when q0 is accepting.
Exam question: May omitted arrows be treated as rejection?
Answer: Only under an explicitly partial notation; a formal complete DFA includes the sink transitions.

6. NFA definition and acceptance

An NFA transition maps a state and symbol to a set of states. Acceptance means at least one complete run ends in an accepting state, not that all runs accept.

Worked example: For binary strings ending in 01, keep scanning in q0 while guessing a 0 that may start the final suffix; q1 reads 1 to final q2.
Exam question: What happens to a branch with no transition?
Answer: It dies; other branches can continue.

7. Epsilon moves and closure

An epsilon transition consumes no input. Epsilon-closure(S) contains S and every state reachable from it using only epsilon moves; apply closure initially and after each symbol transition.

Worked example: If q0 epsilon->q1 and q1 epsilon->q2, closure({q0}) includes all three even before a symbol is read.
Exam question: Can epsilon transitions read an arbitrary symbol?
Answer: No. They consume nothing and must not advance the input position.

8. Subset construction and equivalence

Subset construction turns each reachable set of NFA states into a DFA state. Start with the epsilon-closure of the NFA start; a subset accepts when it intersects the NFA final set. At most 2^n subsets arise for n states.

Worked example: The NFA suffix demo has active set {0,1} after 0 and {0,2} after 01; the latter accepts.
Exam question: Do NFAs recognize a larger language class than DFAs?
Answer: No. Both recognize exactly regular languages; an NFA can be more compact.

NFA subset simulation for strings ending in 01

def accepts(text):
    delta = {(0, "0"): {0, 1}, (0, "1"): {0}, (1, "1"): {2}}
    current = {0}
    for symbol in text:
        if symbol not in {"0", "1"}:
            raise ValueError("binary alphabet required")
        current = {v for u in current for v in delta.get((u, symbol), set())}
    return 2 in current

for text in ["", "01", "1101", "1100", "0101"]:
    print(repr(text), accepts(text))

Checked output:

'' False
'01' True
'1101' True
'1100' False
'0101' True

9. Regular expressions and precedence

Theoretical regular expressions use union, concatenation and star, plus empty-language and empty-string constants. Star binds tighter than concatenation, which binds tighter than union; parentheses remove doubt.

Worked example: (A union B)*AB denotes all A/B strings ending in AB. A union BC denotes A or BC, not (A union B)C.
Exam question: Are all programming regex features regular?
Answer: No. Features such as backreferences can go beyond theoretical regular expressions.

10. Regex, automata and Arden equations

Kleene's theorem equates finite automata and regular expressions. Thompson-style construction combines epsilon-NFA fragments; state elimination combines path expressions. Arden's equation X=AX union B has solution A star B, unique when epsilon is not in A.

Worked example: If X=aX union b and epsilon is not in {a}, solutions are a star b: b,ab,aab,... .
Exam question: Why mention the epsilon restriction?
Answer: It ensures uniqueness in the standard left-concatenation form of Arden's lemma.

11. Closure of regular languages

Regular languages are closed under union, intersection, complement, difference, concatenation, star and reversal. Complementing a DFA requires a fixed alphabet and complete transitions.

Worked example: Build a product DFA for languages L1 and L2; accepting pairs require both components final for intersection.
Exam question: Why not merely flip NFA final states to get complement?
Answer: NFA acceptance is existential over runs; flipping finals does not negate that existential condition.

12. DFA minimization and distinguishing suffixes

Remove unreachable states, partition final versus nonfinal states, then refine until transitions lead to matching equivalence classes. Equivalent states accept exactly the same continuation strings.

Worked example: qA and q0 in the suffix DFA are distinguishable by continuation B: qA accepts AB's completion, while q0 does not.
Exam question: Can two states be merged because both are currently nonfinal?
Answer: Not without checking all future continuation behavior.

13. Regular pumping lemma and quantifiers

If L is regular, some p makes every w in L with length at least p splittable as xyz, with length(xy)<=p, length(y)>0 and xy^i z in L for all i>=0. For nonregularity, defeat every allowed split of your chosen witness.

Worked example: For a^p b^p, every allowed y lies in the initial a block. Pumping i=0 removes a symbols but not b symbols.
Exam question: May you choose a convenient split to prove nonregularity?
Answer: No. The split is chosen adversarially; your argument must cover all allowed splits.

14. Myhill-Nerode and nonregularity

Two prefixes are distinguishable if some suffix makes exactly one resulting string a member. A language is regular exactly when it has finitely many equivalence classes under indistinguishability.

Worked example: For {a^n b^n}, prefixes a^i and a^j with i!=j are distinguished by b^i. Infinitely many distinct classes rule out any finite DFA.
Exam question: Can the pumping lemma prove every regularity claim?
Answer: It is a necessary condition, not a general sufficient test; explicit construction or equivalence tools are stronger.

15. Context-free grammars and derivation

A CFG has variables, terminals, productions and a start variable. Each production replaces one variable; a derivation ends in a terminal string. S->aSb or epsilon generates exactly a^n b^n for n>=0.

Worked example: S=>aSb=>aaSbb=>aabb uses two recursive productions then epsilon.
Exam question: Does a CFG define a particular implementation order?
Answer: No. It defines generated strings; parsing algorithms choose how to recover structure.

16. Parse trees, ambiguity and precedence

A grammar is ambiguous when at least one string has two distinct parse trees, equivalently two distinct leftmost derivations. A language is inherently ambiguous only if every CFG for it is ambiguous.

Worked example: E->E+E or E*E or id permits two parses for id+id*id. Layered E,T,F productions can impose multiplication precedence.
Exam question: Does an ambiguous grammar prove its language inherently ambiguous?
Answer: No. A different grammar may be unambiguous.

17. Grammar simplification, CNF and GNF

Simplification removes useless symbols, unit productions and nullable productions with care to preserve epsilon when needed. CNF uses A->BC or A->a, with a controlled start-to-epsilon exception; GNF uses a leading terminal followed by variables.

Worked example: Replace a terminal embedded in a long production by its own variable, then split the right side into binary pieces for CNF.
Exam question: Can epsilon just be deleted from every nullable production?
Answer: No. Alternative productions must account for omitting nullable occurrences, and start-language membership must be preserved.

18. PDA and stack recognition

A pushdown automaton adds a stack to finite control. A nondeterministic PDA recognizes exactly the context-free languages. Push a marker for each a, then pop for each b, and reject wrong order or mismatched counts.

Worked example: The Python recognizer accepts epsilon,aabb and aaabbb, but rejects aab,abab and ba. Its list simulates one stack.
Exam question: Why can a finite-state counter not replace this stack for arbitrary n?
Answer: Unbounded matching counts require arbitrarily many distinguishable histories.
input: a a b b
stack: [] -> [a] -> [a,a] -> [a] -> []
phase: push a symbols, then pop b symbols
The phase switch prevents returning to the a block. Acceptance requires all input and an empty matching stack.

Stack recognition of a^n b^n

def equal_blocks(text):
    stack = []
    in_b_phase = False
    for symbol in text:
        if symbol == "a" and not in_b_phase:
            stack.append(symbol)
        elif symbol == "b":
            in_b_phase = True
            if not stack:
                return False
            stack.pop()
        else:
            return False
    return not stack

for text in ["", "ab", "aabb", "aaabbb", "aab", "abab", "ba", "ac"]:
    print(repr(text), equal_blocks(text))

Checked output:

'' True
'ab' True
'aabb' True
'aaabbb' True
'aab' False
'abab' False
'ba' False
'ac' False

19. PDA acceptance and determinism

For nondeterministic PDAs, acceptance by final state and acceptance by empty stack define the same CFL class after conversion. Always specify that the entire input must be consumed. Deterministic PDAs recognize a proper subclass of CFLs.

Worked example: A PDA cannot accept aab solely because its stack was empty earlier. A delimiter can make a stack phase switch easy to determine.
Exam question: Are deterministic and nondeterministic PDAs equally powerful?
Answer: No. This differs from the DFA/NFA equivalence.

20. CFL closure and decision questions

CFLs are closed under union, concatenation and star, and intersection with a regular language. They are not closed under arbitrary intersection or complement. CFG membership and emptiness are decidable; general CFG equivalence is undecidable.

Worked example: Intersect a CFL with a DFA language by tracking finite control alongside the stack. A stack cannot in general enforce two independent unbounded equalities.
Exam question: Does decidable membership imply decidable equivalence?
Answer: No. Asking about one string differs from comparing all strings in two languages.

21. CFL pumping and the triple-count language

The CFL pumping lemma splits w=uvxyz, with length(vxy)<=p, length(vy)>0, and uv^i xy^i z in L for every i>=0. Both v and y pump together. To refute a CFL, cover all valid splits.

Worked example: For a^p b^p c^p, the short window vxy cannot touch both a and c blocks. Pumping down changes at least one count and leaves at least one other unchanged, breaking equality.
Exam question: Why is pumping two pieces necessary?
Answer: A grammar branch can grow two coordinated sides, unlike the single regular-language pump.

22. Chomsky hierarchy

Regular languages fit finite automata; context-free languages fit nondeterministic PDAs; context-sensitive languages fit linear-bounded automata; recursively enumerable languages fit Turing recognizers. These language classes form strict inclusions.

Worked example: a^n b^n is context-free but not regular; a^n b^n c^n is context-sensitive but not context-free. Epsilon conventions need care in noncontracting grammars.
Exam question: Does every decidable language have to be context-sensitive?
Answer: No. Decidability is a different boundary; linear-space restrictions can exclude some decidable languages.
Regular
  strictly inside Context-free
    strictly inside Context-sensitive
      strictly inside Turing-recognizable
Chomsky language hierarchy; decidable languages also lie within Turing-recognizable languages but are not one of these four grammar levels.

23. Turing machine definition and configurations

A Turing machine has finite control, a tape alphabet including blank, an unbounded tape model and a head that reads, writes and moves. A configuration records state, tape content and head position.

Worked example: To decide a^n b^n, repeatedly mark one unmarked a and one corresponding b, reject order/count errors and accept when both groups are exhausted.
Exam question: Is the tape literally infinite hardware?
Answer: No. It is a mathematical model with no fixed finite bound on available cells.

24. Machine variants and Church-Turing thesis

Multitape and nondeterministic Turing machines have the same computability power as the standard model, though simulation costs can differ. The Church-Turing thesis relates effective computation to Turing computability, not a theorem about all imaginable physics.

Worked example: Several tapes can simplify an algorithm's description without enabling it to decide the general halting problem.
Exam question: Does equivalent computability mean equal running time?
Answer: No. A simulation may incur additional time or space.

25. Recognizers, deciders and complements

A decider halts with the correct answer on every input. A recognizer accepts members, but may reject or loop on nonmembers. A language is decidable iff both it and its complement are recognizable.

Worked example: Run a recognizer for L and one for its complement in alternating steps; exactly one eventually accepts, yielding a total decision.
Exam question: Why not run the first recognizer until it stops, then the second?
Answer: The first may never stop; dovetailing prevents that starvation.

26. Universal simulation and enumerators

A universal Turing machine simulates a supplied encoded machine on supplied input. An enumerator prints language members, possibly with repetition and no order guarantee. Enumerability and recognizability are equivalent.

Worked example: To recognize a word from an enumerator, run it until that word is printed. A nonmember may never appear.
Exam question: Does never having appeared yet prove nonmembership?
Answer: No. The enumeration can be arbitrarily delayed.

27. Undecidability and the halting contradiction

The halting problem has no decider for all program-input pairs. Assume a decider H; construct D that loops when H predicts D's input-machine halts on itself and halts otherwise; running D on its own code contradicts H.

Worked example: The contradiction concerns a total exact predictor for arbitrary programs, not whether one particular loop can be analyzed.
Exam question: Is the halting language recognizable?
Answer: Yes. Simulate the machine and accept if it halts; nonhalting runs can loop forever.

28. Mapping reductions, PCP and Rice's theorem

A computable mapping reduction A<=m B transforms membership in A into membership in B. To prove B undecidable, reduce a known undecidable A to it. PCP asks for a nonempty tile-index sequence with equal top/bottom concatenations; it is undecidable in general.

Worked example: Rice's theorem covers every nontrivial property of the language recognized by a Turing machine, not its syntax or step count.
Exam question: Does Rice's theorem make testing whether code contains a loop undecidable?
Answer: No. That is a syntactic property, outside the theorem's semantic-language scope.

29. Complexity, P and NP

Computability asks whether an algorithm exists; complexity asks its resource use. P contains polynomial-time decision problems; NP has polynomial-time verifiable yes-certificates. P subset NP; equality is unresolved.

Worked example: A proposed Hamiltonian cycle is easy to verify by checking vertices and edges; finding one is a separate task.
Exam question: Does NP mean not polynomial?
Answer: No. It means nondeterministic polynomial time, equivalently certificate verification.

30. Proof and revision checklist

Choose the language class, define the machine or grammar, trace examples and prove the claim. For impossibility arguments, state the quantifiers or reduction direction. For deciders, explicitly establish halting on every input.

Worked example: Classify ends-in-AB as regular, a^n b^n as CFL but nonregular, and general halting as recognizable but undecidable.
Exam question: What is the most common proof mistake?
Answer: Using examples as a universal proof, choosing only one pumping split, or reducing in the wrong direction.

Machine and language comparison

ModelMemoryLanguage class / limit
DFA / NFAFinite controlRegular; NFA is not more powerful
NPDAFinite control plus stackContext-free
DPDAFinite control plus deterministic stackProper subset of context-free
LBATape bounded linearly in input lengthContext-sensitive
Turing recognizerUnbounded tape modelMay loop on nonmembers
Turing deciderUnbounded tape modelAlways halts with the right answer

Closure and decision reference

Class / questionYesNo / caution
Regular closureUnion,intersection,complement,concat,starComplete DFA and fixed alphabet for complement
CFL closureUnion,concat,star,intersection with regularNot general intersection or complement
DFA membership / equivalenceDecidableAn NFA may expand exponentially when determinized
CFG membership / emptinessDecidableGeneral CFG equivalence undecidable
Turing language membershipRecognizable in generalNot decidable in general
P versus NPP is a subset of NPEquality remains unresolved

Proof mistakes to avoid

  • Do not confuse epsilon, the empty language, and {epsilon}.
  • A final state visited before the input ends does not guarantee acceptance.
  • For nonregularity or non-context-freeness, cover every permitted pumping split.
  • A DFA can be complemented by flipping finals only after completing transitions.
  • Do not claim a recognizer rejects merely because it has not yet accepted.
  • A reduction into a known undecidable problem does not by itself prove your problem undecidable; reduce from the known hard problem.
  • State whether a theorem concerns syntax, language semantics, decidability or complexity.

Practice resources and sources

The following references support the definitions and proof methods. Page examples, code and diagrams are original teaching material.

Comments

Popular posts from this blog

Big Data Analytics Exam Prep

Process States in OS: Diagram, PCB and Context Switching

Python Mutable Default Arguments and Shallow Copies: Why Lists Keep Changing