{
"cells": [
{
"cell_type": "markdown",
"id": "06fc7a12-98fd-4724-9970-5951c63c0b5c",
"metadata": {},
"source": [
"# PDAs and context-free grammars\n",
"\n",
"\n",
"Star\n",
"Issue\n",
"Watch\n",
"Follow\n",
"\n",
"Moving on from DFAs, NFAs and regular languages, we next consider more powerful models of computation, namely pushdown automata (PDAs) and context-free grammars (CFGs).\n",
"These turn out to be analogous to finite-state automata and regular languages, but are more powerful.\n",
"In particular, we will show that CFGs and PDAs are equivalent and that they are strict supersets of regular languages and NFAs.\n",
"\n",
"\n",
"## Context-free grammars\n",
"\n",
"A CFG consists of variables and terminal symbols, as well as rules which expand these variables into strings of other variables and terminal symbols.\n",
"\n",
"\n",
":::{prf:definition} Context-free grammar\n",
"\n",
"A context-free grammar (CGG) is a 4-tuple $(V, \\Sigma, R, S)$, where\n",
"\n",
"1. $V$ is a finite set called the variables,\n",
"2. $\\Sigma$ is a finite set that is disjoint from $V$, called the terminals,\n",
"3. $R$ is a finite set of rules, with each rule being a pair consisting of a variable and a string of variables and terminals,\n",
"4. $S \\in V$ is the start variable.\n",
"\n",
":::\n",
"\n",
"\n",
"We now introduce some terminology on CFGs.\n",
"We say that a string yields another if the latter can be obtained by applying a rule of a CFG onto the former.\n",
"Similarly, we say that a string derives another if the latter can be obtained by applying a finite number of rules to it.\n",
"\n",
":::{prf:definition} Yields, derives\n",
"\n",
"If $A \\to w$ is a rule of a CFG, we say that $uAv$ yields $uwv$, written $uAv \\implies uwv$.\n",
"We say that $u$ derives $v$, written $u \\stackrel{*}{\\implies} v$, if a sequence $u_1, u_2, \\dots u_k$ exists for some $k \\geq 0$ such that\n",
"\n",
"$$u \\implies u_1 \\implies \\dots \\implies u_k \\implies v.$$\n",
"\n",
":::\n",
"\n",
"\n",
"Similarly to DFAs and NFAs, we define the language of a CFG to be the set of strings it can represent, i.e. the set of strings that can be derived from it.\n",
"\n",
":::{prf:definition} Context-free language\n",
"\n",
"We define the language of a CFG $G$ with terminals $\\Sigma$ and start variable $S$, to be the set $L(G) \\equiv \\{w \\in \\Sigma^* | S \\stackrel{*}{\\implies} w\\}.$\n",
"\n",
":::"
]
},
{
"cell_type": "markdown",
"id": "9c47ae32-7a8e-4f45-9f40-bef2d0b3a788",
"metadata": {
"editable": true,
"slideshow": {
"slide_type": ""
},
"tags": []
},
"source": [
"We can now look at a couple of examples of CFGs and strings that these generate.\n",
"We can visualise the derivation of a string in a language using a parse tree, where each node is a variable or terminal symbol and each edge corresponds to part of a substitution rule.\n",
"First is the following example of a CFG which generates all strings of the form $\\texttt{0}^k\\texttt{1}^k$ for some $k \\geq 0$.\n",
"We already know that this set of strings is not a regular language.\n",
"Therefore, this example shows that the set of context-free languages (CFLs) is not equal to the set of regular languages.\n",
"\n",
":::{prf:example} Example CFG\n",
"\n",
"Consider the CFG $G_1 = (V, \\Sigma, R, S)$ where $V = \\{S, E\\}, \\Sigma = \\{\\texttt{0}, \\texttt{1}\\}$ and $R$ consists of the rules\n",
"\n",
"$$\\begin{align}\n",
"S &\\to \\texttt{0}S\\texttt{1} \\\\\n",
"S &\\to E \\\\\n",
"E &\\to \\epsilon\n",
"\\end{align}$$\n",
"\n",
"Below is an example of a derivation of the string $\\texttt{0011}$ using this language.\n",
":::"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "2f5a7972-8dbd-4077-bb23-1b8688321e0a",
"metadata": {
"editable": true,
"slideshow": {
"slide_type": ""
},
"tags": [
"remove-cell"
]
},
"outputs": [],
"source": [
"import cairosvg\n",
"import nltk\n",
"\n",
"from nltk import CFG\n",
"from nltk.parse import RecursiveDescentParser\n",
"from IPython.display import Image, display\n",
"\n",
"def parse_and_show_trees(grammar, sentence):\n",
" \"\"\"\n",
" Given a CFG `grammar` and a sentence `sentence`, parse `sentence` and show\n",
" the parse trees associated with this sentence.\n",
"\n",
" Arguments:\n",
" grammar: CFG, context free grammar to use\n",
" sentence: str, string to parse\n",
" \"\"\"\n",
"\n",
" # Create a parser from the grammar and parse the string\n",
" parser = RecursiveDescentParser(grammar)\n",
" trees = list(parser.parse(sentence))\n",
"\n",
" # Check at least one parse tree exists\n",
" assert len(trees) > 0, f\"Sentence not in the CFG.\"\n",
"\n",
" # Parse the sentence and get the first parse tree\n",
" for tree in trees:\n",
" \n",
" parse_tree_png = cairosvg.svg2png(\n",
" tree._repr_svg_(),\n",
" background_color=\"white\",\n",
" )\n",
" \n",
" display(Image(parse_tree_png))"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "1059ad58-39b7-4145-b22f-a0257d1b6e4c",
"metadata": {
"editable": true,
"slideshow": {
"slide_type": ""
},
"tags": [
"center-output",
"remove-input"
]
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAHgAAACoCAIAAACkOL2qAAAABmJLR0QA/wD/AP+gvaeTAAAJzUlEQVR4nO2dX0hT7x/HnzmVGSwTs9Smqy2VnFkakiUusFD6khoiCOt/F2IUCGJFLtIL86IikApEI7pRsCgl0gtJ8Q+ktIuQjRSDJbVMtKHzT06nnt/Fgf1itbNz9NnzZz2vK8840bt3n/PmvdM5n2QcxwGG/wnCLeBfgRmNCGY0IpjRiKDJ6NHR0eTkZJ1Op9frd+7cqdFo2tvbcYsSSzBuARK4fPlyUFCQ2WyWyWQTExN5eXk2mw23KLHQNNEWi8XhcPz69QsAEBsb++TJE4qMBhw9XLhwAQCQkpIyMjLCf+JwOPBKEg9NRo+NjanVagCAQqG4d+/e+vo6bkUSoMlojuOmpqaKi4v5a9FgMKysrOBWJBbKjOZpbm5WKpUAgOrqatxaxEKN0X19fWaz2X346tUrAEBqaipGSZKgpnXMzs7eunXLfZifnx8SEjI/P49RkiSoMVqj0bx9+/bx48f8YW9vr8vlKigowKtKPDKOktuki4uLarU6OjpaoVDs2LGju7u7uLi4qalpy5YtuKWJghqjAQA2m02lUs3NzY2Pj8fHx2/btg23IgnQZDTVUJPRbhwOh8PhwK1CMjQZvby8XFtbGxcXFxcXV1tbu7y8jFuRBKiJjp6enmvXrmm1Wq1WK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zErUIypDyILp6JiQncEjYCfRNNKcxoRDCjEcGMRgQzGhHMaEQwoxHBjEYEMxoRzGhEMKMRwYxGBDMaEcxoRDCjEcGMRgQzGhHMaEQwoxHBjEYEMxoRzGhEMKMRwYxGBDMaEcxoRDCjEcEe20UEm2hEMKMRwYxGBDMaEXQYff369YiICJlMplars7Kyjh49evDgwbCwsMzMTNzSRIPgzS8oXLlyBQDw+vVr9ycWiyU9PR2jJEnQMdEAgKioKADA72/PabXapqYmfIqkQY3Rf5KXl5eeno5bhVgoe1movb3darWurKwMDQ2NjY3hliMByiZaLpfL5fLg4GC5XI5bizQom+j8/PzCwkL+Z71ej1eMJCib6N/hFxw4nU7cQkRBsdEKhaKzs/P27du4hYiCGqP51Sp2u939yeDgYGlp6bFjx/CJkgAdt0krKiqePn06Pz8fFhYWGxu7vr4+MzMzOzsrl8vtdnt4eDhugb6hw+gAgJrooB1mNCKY0YhgRiOCGY0IZjQimNGI+B/roh9YK/ZfKQAAAABJRU5ErkJggg==",
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Define CFG\n",
"grammar = CFG.fromstring(\n",
" \"\"\"\n",
" S -> '0'S'1'\n",
" S -> E\n",
" E -> \n",
" \"\"\"\n",
")\n",
"\n",
"# Define a sentence to parse\n",
"parse_and_show_trees(grammar=grammar, sentence=list(\"0011\"))"
]
},
{
"cell_type": "markdown",
"id": "01b793fe-0ad2-4a8b-a408-c432c8abffc0",
"metadata": {
"editable": true,
"slideshow": {
"slide_type": ""
},
"tags": []
},
"source": [
"We also have the following example CFG which generates valid mathematical expressions involving sums and multiplications.\n",
"CFGs similar to this can be used to define parsers for programming languages.\n",
"\n",
":::{prf:example} Example CFG for mathematical expressions\n",
"\n",
"Consider the CFG $G_2 = (V, \\Sigma, R, S)$ where $V = \\{E, T, F\\}, \\Sigma = \\{\\texttt{a}, \\texttt{(}, \\texttt{)}\\}, S = E$ and $R$ consists of the rules\n",
"\n",
"$$\\begin{align}\n",
"E &\\to T~|~F+T \\\\\n",
"T &\\to F~|~F*T \\\\\n",
"F &\\to \\texttt{(}E\\texttt{)}~|~\\texttt{a} \\\\\n",
"\\end{align}$$\n",
"\n",
"Below is an example of a derivation of the string $\\texttt{a*(a+a)}$ using this language.\n",
":::"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "709c12b1-c273-4579-91b1-1af02c026204",
"metadata": {
"editable": true,
"slideshow": {
"slide_type": ""
},
"tags": [
"center-output",
"remove-input"
]
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAKgAAAFoCAIAAABMtifjAAAABmJLR0QA/wD/AP+gvaeTAAATb0lEQVR4nO3dfUxT5xcH8KctY4BU0YC6ZtooiALCpGORieiCCGp4U5xm+JKgGdFlg+lkLmLEZc5/WIguv+gsAxPdRB0iWSImOpiTOdzQbEQNglpRAY2KpaDFlpf7++M6ZLW9tLftfe7tOZ+/WK3tGV+f09OWHmQMwxAEj5x2AYgODB4oDB4oDB4oWMHn5+ePHTtWJpOp1eq4uLg5c+bMmjXL19c3NjaWdmmCY4DZuHEjIaSysnLokqtXr2o0GoolUQHrxBNCgoKCCCFy+cv/8eDg4JKSEnoV0QEu+FclJydrNBraVQjNi3YBdFRVVel0OrPZfPHixZaWFtrlUAD0xCsUCoVC4eXlpVAoaNdCB9ATn5qamp6ezn49b948usVQAfTED3fmzBlCyPPnz2kXIigMnvj4+FRXV2/fvp12IYICF/zdu3cJIZ2dnUOX1NfX5+TkzJ8/n15RFMgYSG/Lbt68+fvvv+/p6fH19VWpVIODg3q9vqurS6FQdHZ2jhkzhnaBwoEVPBoCrtUjFgYPFNzgtVqtVqulXQU1QF/AIYR0dHTQLoEmuCceOAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKAweKPx8PFB44oHC4IHC4IHC4IGCFXxMTIxcLler1eHh4TKZTKlURkREBAYGymSyoqIi2tUJClbwJpOprq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4O0i6HEFfsz+cBXPDsL4+pqKjo6+s7fPiw2Wy+fPny9OnT/f39aZVEZ3++ux9LxObBgwehoaEKhSIxMbG0tNTb2zsmJsZgMNCqx7X78+0H8f14hmF6enpGjx5NCDEajX5+frQrogBi8IgAfB6PWBi8WOC+eqBwXz0SAgYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFAYPFH5MGig88UBh8EBh8EBh8EBh8EBh8EBh8EBh8PTR2Z8v2CpFZFVbW9vrr79eVlbGMMy6detiY2OFuV888ZTR2p+PL9nSxzBMRUXFoUOH7ty509zcbDKZBLhTPPH0UdmfjwsOKaO1Px+Dp4za/nxhZkhkC639+Tjc0cfQ2J+PwQOFUz1QGDxQGDxQGDxQGDxQGDxQ/weUxdIpyNLKSgAAAABJRU5ErkJggg==",
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Define CFG\n",
"grammar = CFG.fromstring(\n",
"\"\"\"\n",
" E -> T | F'+'T\n",
" T -> F | F'*'T\n",
" F -> '('E')' | 'a'\n",
"\"\"\"\n",
")\n",
"\n",
"# Define a sentence to parse\n",
"parse_and_show_trees(grammar=grammar, sentence=list(\"a*(a+a)\"))"
]
},
{
"cell_type": "markdown",
"id": "6d33e6cf-2727-4ce4-b4da-7d02e4445f34",
"metadata": {},
"source": [
"Sometimes, a string in a CFL can be derived in more than one way (even if we account for applications of the same rules in different orders).\n",
"In such cases, the language is ambiguous in the sense that there may be more than one parse tree that correspond to the same given string.\n",
"The following definitions formalise this notion.\n",
"\n",
":::{prf:definition} Leftmost derivation\n",
"\n",
"We call a derivation of a string in a CFG a leftmost derivation if at every step of the derivation the leftmost variable is the one that is replaced.\n",
":::\n",
"\n",
"\n",
"This idea allows us to succinctly define ambiguous languages.\n",
"\n",
":::{prf:definition} Ambiguity\n",
"\n",
"We say that a string $w$ is derived ambiguously from a CFG $G$, if there is more than one leftmost derivation of $w$ in $G$.\n",
"If a CFG $G$ contains a string that can be derived ambiguously, we say that $G$ is ambiguous.\n",
"If a CFL can only be generated by an ambiguous CFG, we say it is inherently ambiguous.\n",
":::\n",
"\n",
"Some CFLs are inherently ambiguous, which means that they can be generated only by ambiguous grammars."
]
},
{
"cell_type": "markdown",
"id": "8b684ea1-5bc9-448d-8e37-a25f7cc78b31",
"metadata": {},
"source": [
"## Chomsky normal form\n",
"\n",
":::{prf:definition} Chomsky normal form\n",
"\n",
"A context-free grammar is in Chomsky normal form if every rule is of the form\n",
"\n",
"$$\\begin{align}\n",
"A &\\to BC\n",
"A &\\to a\n",
"\\end{align}$$\n",
"\n",
"where $a$ is any terminal and $A,$ $B,$ and $C$ are any variables, except that $B$ and $C$ may not be the start variable.\n",
"In addition, we permit the rule $S \\to \\epsilon$ where $S$ is the start variable.\n",
"\n",
":::\n",
"\n",
"\n",
":::{prf:lemma} CFLs generated by CFG in Chomsky normal form\n",
"\n",
"Any context-free language is generated by a context-free grammar in Chomsky normal form.\n",
"\n",
":::\n",
"\n",
"\n",
":::{dropdown} Proof: CFLs generated by CFG in Chomsky normal form\n",
"\n",
"Let $L$ be a CFL.\n",
"Then there exists a CFG $G = (V, \\Sigma, R, S)$ that generates it.\n",
"We will convert $G$ into an equivalent CFG $G'$ in normal form by adding a new start variable, then eliminating all $\\epsilon$-rules of the form $A \\to \\epsilon,$ all unit rules of the form $A \\to B,$ and converting all remaining rules in proper form.\n",
"\n",
"__Step 1:__\n",
"First, define a new start variable $S_0$ and the rule $S_0 \\to S.$\n",
"This ensures that the start variable does not occur in the right hand side of a rule.\n",
"\n",
"__Step 2:__\n",
"Second, we eliminate all $\\epsilon$-rules of the form $A \\to \\epsilon$ as follows.\n",
"For each occurrence of a rule of the kind $A \\to \\epsilon,$ first we remove the rule and then for each occcurence of $A$ on the right hand side of any other rule, we add a new rule with that occurence deleted.\n",
"For example, if we remove $A \\to \\epsilon$ and there is another rule of the form $R \\to uAvAw$ (where $u, v, w$ are strings of terminals and variables) we add the rules $R \\to uvAw, R \\to uAvw$ and $R \\to uvw$ to the grammar.\n",
"We repeat these steps until we have removed all $\\epsilon$-rules not involving the start variable.\n",
"This procedure is guaranteed to terminate because at each step the number of $\\epsilon$-rules decreases by one, until it reaches zero.\n",
"\n",
"__Step 3:__\n",
"Third, we handle unit rules.\n",
"If there is a unit rule of the form $A \\to B$ we remove it.\n",
"Then for each occurence of a rule of the type $B \\to u$ (where $u$ is a string of terminals and variables) appears, we add $A \\to u,$ unless this was a unit rule that we removed previously.\n",
"We repeat this step until we have removed all unit rules.\n",
"This procedure is also guaranteed to terminate: there is a finite set of variables and thus a finite set of unit rules; since at each step we remove a unit rule and do not allow it to be re-introduced later in this procedure, at some point we will have removed all unit rules, and the procedure will terminate.\n",
"\n",
"__Step 4:__\n",
"Last, we convert all remaining rulles in proper form.\n",
"We replace each rule $A \\to u_1 \\dots u_k, k \\geq 3,$ where each $u_i$ is a variable or terminal symbol, with the rules $A \\to u_1 A_1, A_1 = u_2 A_2 \\dots, A_{k-2} \\to u_{k-1} u_k,$ where the $A_i$ are new variables.\n",
"We replace every terminal $u_i$ in the preceeding rules with a new variable $U_i$ and add the rule $U_i \\to u_i.$\n",
"We repeat this step until all the rules are in proper form.\n",
"Again, this procedure guaranteed to terminate since it is applied exactly once for every rule that was not originally in normal form.\n",
"\n",
"The grammar $G'$ that results after these steps satisfies the requirements for being in Chomsky normal form, as required.\n",
"\n",
":::"
]
},
{
"cell_type": "markdown",
"id": "67af39a2-ac86-4f34-a869-0b69ad09e765",
"metadata": {},
"source": [
"## Pushdown Automata\n",
"\n",
"Now we move to pushdown automata (PDA), which are another kind of computational model.\n",
"PDAs are similar to NFAs in that they have a finite number of states and allow for nondeterminism.\n",
"We will show that PDAs have the same expressive power as CFGs, in a somewhat analogous way that NFAs have the same power as regular expressions.\n",
"It will turn out that PDAs are very useful in this sense because they provide another way to prove things about CFLs, in addition to CFGs.\n",
"PDAs extend NFAs by introducing a stack of symbols, from which they can read symbols as well as add new ones or remove existing symbols.\n",
"The stack itself can be of infinite length, which is what makes PDAs more powerful than NFAs.\n",
"\n",
"\n",
":::{prf:definition} Pushdown automaton (PDA)\n",
"\n",
"A pushdown automaton is a $6$-tuple $(Q, \\Sigma, \\Gamma, \\delta, q_0, F),$ where $Q, \\Sigma, \\Gamma$ and $F$ are all finite sets, and\n",
"\n",
"1. $Q$ is a finite set, the set of states,\n",
"2. $\\Sigma$ is a finite set, the input alphabet,\n",
"3. $\\Gamma$ is a finite set, the stack alphabet,\n",
"4. $\\delta : Q \\times \\Sigma_\\epsilon \\times \\Gamma_\\epsilon \\to \\mathcal{P}(Q \\times \\Gamma_\\epsilon)$ is a function, the transition funciton,\n",
"5. $q_0 \\in Q$ is the start state,\n",
"6. $F \\subseteq Q$ is the set of accept states.\n",
"\n",
":::\n",
"\n",
"Crucially a PDA can only read, write or remove symbols at the top of the stack.\n",
"Now we define what it means for a PDA to accept a string, which is analogous to an NFA accepting a string.\n",
"\n",
"\n",
":::{prf:definition} PDA accepts\n",
"\n",
"A pushdown automaton $M = (Q, \\Sigma, \\Gamma, \\delta, q_0, F)$ acccepts an input $w$ if it can be written in the form $w = w_1w_2 \\dots w_m, w_i \\in \\Sigma_\\epsilon,$ and there exist sequences of states $r_0, r_1, \\dots, r_m \\in Q$ and strings $s_0, s_1, \\dots, s_m \\in \\Gamma^*$ that satisfy\n",
"\n",
"1. $r_0 = q_0$ and $s_0 = \\epsilon.$\n",
"2. For $i = 0, \\dots, m - 1,$ we have $(r_{i+1}, b) \\in \\delta(r_i, w_{i+1}, a),$ where $s_i = at, s_{i+1} = bt$ with $a, b \\in \\Gamma_\\epsilon$ and $t \\in \\Gamma^*.$\n",
"3. $r_m \\in F.$\n",
"\n",
":::"
]
},
{
"cell_type": "markdown",
"id": "cb757542-f493-4e1e-ba7b-30c4108f1172",
"metadata": {
"editable": true,
"slideshow": {
"slide_type": ""
},
"tags": []
},
"source": [
"## Context Free Pumping Lemma\n",
"\n",
":::{prf:theorem} Pumping Lemma for CFLs\n",
":label: toc-cfl-pumping-lemma\n",
"\n",
"For every CFL $A$, there exists an integer $p$ such that if $s \\in A$ and $|s| \\geq p$, then $s = uvxyz$ where\n",
"\n",
"1. $uv^ixy^iz \\in A$ for all $i \\geq 0$,\n",
"2. $vy \\neq \\epsilon$,\n",
"3. $|vxy| \\leq p$.\n",
"\n",
":::"
]
},
{
"cell_type": "markdown",
"id": "f13d6e35-a51c-45c7-b19b-022157a626fb",
"metadata": {},
"source": [
"::::{prf:example} A non-context-free language\n",
"\n",
"\n",
"The language $A = \\{0^k1^k2^k | k \\geq 0\\}$ is not a CFL.\n",
"\n",
":::{dropdown} Proof\n",
"\n",
"Suppose $A = \\{0^k1^k2^k | k \\geq 0\\}$ is CFL.\n",
"Then by the {ref}`pumping lemma for CFLs`, it has a pumping length $p$.\n",
"Let $s = 0^p 1^p 2^p$.\n",
"By the pumping lemma, it holds that $s = uvxyz$, such that the pumping lemma conditions hold.\n",
"By the condition $|vxy| \\leq p$, the substring $vxy$ cannot both contain both zeros andd twos.\n",
"Therefore, $uv^ixy^iz$ will not contain equal numbers of zeros and twos when $i \\geq 2,$ which contradicts the pumping lemma.\n",
"So $A$ is not a CFL.\n",
":::\n",
"::::"
]
},
{
"cell_type": "markdown",
"id": "beeacaed-ec5c-4cfa-a832-6d371926b45e",
"metadata": {},
"source": [
"::::{prf:lemma} CFL not closed under intersection\n",
"\n",
"The class of context-free languages are not closed under intersection.\n",
"\n",
":::{dropdown} Proof\n",
"\n",
"The languages $A_1 = \\{0^k 1^k 2^l | k, l \\geq 0\\}$ and $A_2 = \\{0^l 1^k 2^k | k, l \\geq 0\\}$ are context free since we can build PDAs that recognise them.\n",
"For example, for $A_1$ we can construct a PDA which pushes the zeros on its stack, then pops them as it reads the ones, and lastly read any number of twos.\n",
"Similarly we can build a PDA that recognises $A_2$.\n",
"However, $A_1 \\cap A_2 = \\{0^k 1^k 2^k | k \\geq 0 \\}$, which is not a CFL, so the class of CFLs is not closed under intersection.\n",
":::\n",
"::::"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "venv-rw",
"language": "python",
"name": "venv-rw"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.4"
}
},
"nbformat": 4,
"nbformat_minor": 5
}