Lecture 10 CFG 17052023 041739pm
Lecture 10 CFG 17052023 041739pm
Lecture 10 CFG 17052023 041739pm
1
Lecture 10
Amna Iftikhar
CFGs
3
Context-free grammars (CFGs)
Context-free grammars (CFGs) are used to describe context-free
languages.
the single nonterminal on the left hand side can always be replaced by
the right hand side.
6
Context Free Grammar
A grammar consists of:
a set of variables one of which is designated the start variable; It
is customary to use upper-case letters for variables;
S as a start variable:
S V | VV | t | V t | t V
*
9
A A | AB | a | Aa | b B | ᵋ
10
Examples:
CFG for the language that contain words of one length
character
RE = a + b
CFG : S→A
S →a | b A→ a | b
RE = (a + b)(a + b)
CFG : S →AA
S → aa | ab | ba | bb A→a |b
11
Examples:
CFG for the language that contain at most 3 character words
RE
ᵋ ᵋ
= (a + b + ) (a + b + ) (a + b + )ᵋ
CFG :
S →A AA
A → a|b|
ᵋ
CFG for the language that contain at most 3 character words, but start with
a.
RE
ᵋ ᵋ
= a(a + b + ) (a + b + )
CFG : AA
ᵋ
S →a
A → a|b|
12
Examples:
RE = a
CFG :
S →a
S S
S →A
a
A → Aa |a
aa
13
Examples:
CFG for the language that contain at least one a. Σ = {a}
RE = a+ {a,aa,aaa,aaaa,…………..}
CFG :
S →A S→A
A → Aa |a A → aA
A→ a
CFG for the language that contains words of any length. Σ = {a,b} S → AB
S→A A → aA
RE = (a+b)* S →A A → aA A→ a
CFG : A → aA A→a A→ ᵋ
S →A A→a
A → bA
A→
A→B
ᵋ A→ B
B → bB
A → aA | a | b | bA |
ᵋ A→b B → bB B→b
A→ ᵋ B→b
B→ ᵋ
B→
B→A
ᵋ B→A
14
Examples:
CFG for the language that contain at least one a. Σ = {a}
RE = a+ {a,aa,aaa,aaaa,…………..}
CFG :
S →A S→A
A → Aa |a A → aA
A→ a
CFG for the language that contains words of any length. Σ = {a,b}
RE = (a+b)* S →A
CFG : A → aA
S →A A→a
A → bA
A → aA | a | b | bA |
ᵋ A→b
A→ ᵋ
15
CFG Continues…..
CFG for a language that contains at least two characters
with start and end with same symbol
S
CFG:
S → aAa P-1
a a S → aAa | bAb
A
S → bAb P-2 A→ aA | bA | a | b
A → aA P-3
b A
A → bA P-4
A→a P-5 a A
A→b P-6
A→
ᵋ P-7 b A
X
Xy
X123
Number_1
26
CFG for Arithmetic Expression S
AE = a+(b*c)
E
CFG:
S→E P-1
E + E
E → (E) P-2
E→E+E P-3 a ( E )
E→E*E P-4
E→a P-5
E * E
E→b P-6
E→ c P-7 b c
Production Sequence:
P1 → P3 → P5(L) → P2(R) →P4(C) →P6(L) →P7(R)
27