Context Free Grammar (CFG) and Languages(CFL)
Context Free Language:
● Definition: Let L be a language. Then L is a context-free language if and only
if there exists a context-free grammar G such that L = L(G).
Context Free Language:
● The class of context-free languages generalizes over the class of regular
languages, i.e., every regular language is a context-free language.
● The reverse of this is not true, i.e., every context-free language is not
necessarily regular. For example, as we will see {0k1k | k≥0} is context-free
but not regular.
● Definition: Let G1 and G2 be context-free grammars. Then G1 and G2 are
equivalent if and only if L(G1) = L(G2).
Context Free Grammar
● Informally, a CFG consists of:
○ A set of replacement rules, each having a Left-Hand Side (LHS) and a Right-Hand
Side (RHS).
○ Two types of symbols; variables /Non Terminals and terminals.
○ LHS of each rule is a single variable (no terminals).
○ RHS of each rule is a string of zero or more variables and terminals.
Context Free Grammar
● Formally, a Context-Free Grammar (CFG) is a 4-tuple:
G = (V, T, P, S)
V - A finite set of variables or non-terminals
T - A finite set of terminals (V and T do not intersect: do not use
same symbols)
This is our ∑
P - A finite set of productions, each of the form A –> α, where A is in
V and
α is in (V ∪ T)*
Note that α may be ε
● Describe the language generated by following CFG.
G = ({A, B, C, S}, {a, b, c}, P, S)
P:
(1) S –> ABC
(2) A –> aA
(3) A –> ε
(4) B –> bB
(5) B –> ε
(6) C –> cC
(7) C –> ε
7
● Example CFG for ?:
G = ({A, B, C, S}, {a, b, c}, P, S)
P:
(1) S –> ABC
(2) A –> aA A –> aA |
ε
(3) A –> ε
(4) B –> bB B –> bB | ε
(5) B –> ε
(6) C –> cC C –> cC | ε
(7) C –> ε
● Example Derivations:
S => ABC (1)
S => ABC
(1)
=> BC (3)
=> aABC
(2)
=> C
(5)
=> aaABC (2) 8
=> ε (7)
Write CFG For given Language
Exercises
Exercises
. Give a context-free grammar (CFG) for each of the following languages over the alphabet Σ = {a, b}:
Example1 : Write CFG
Example 2 : Write CFG
Write CFG containing substring “abb”
S🡪 XabbX
X🡪aX | bX |
Example 4 : Write CFG
Write the grammar for the language represented by R.E .
Example 5 : Write CFG
Solution
Solution
RE=
Example 3 : Write CFG
Write CFG for following languages:
1. L={ ai bj ck | i=j+k, I,j,k ≥ 0}
2. L={ am+n bm cn | n,m ≥ 0}
3. L={ 0m 1n 0m+n | n,m ≥ 0}
4. L={ an bm an | n ≥ 0, m ≥ 1 }
5. L={ an bn cm dm | n,m ≥ 1} U {am bn cn dm | n,m ≥ 1}