SlideShare a Scribd company logo
Context-Free Grammar
Presented by: Mohammad Ilyas Malik
M.Tech cse-3rd sem
OUTLINE
• Context-Free Grammar Introduction
• Derivation Tree/Parse Tree
• Sentential Form and Partial Derivation Tree
• Types of Derivation Tree
• Left and Right Recursive Grammars
• Ambiguity in Context-Free Grammars
• CFG Simplification
Context-Free Grammar Introduction
Grammar: Grammar is a set of rules which check whether a string belong to a particular
language or not.
Context-Free Grammar:
• It is a notation used to specify the syntax of language.
• Context free grammar are used to design parser.
Definition: A context-free grammar (CFG) consisting of a finite set of grammar rules is
a quadruple (N, T, P, S) where
• N is a set of non-terminal symbols.
• T is a set of terminals where N ∩ T = NULL.
• P is a set of rules, P: N → (N U T)*, i.e., the left-hand side of the production rule P does have
any right context or left context.
• S is the start symbol.
Example
• The grammar ({A}, {a, b, c}, P, A), P : A → aA, A → abc.
• The grammar ({S, a, b}, {a, b}, P, S), P: S → aSa, S → bSb, S → ε
• The grammar ({S, F}, {0, 1}, P, S), P: S → 00S | 11F, F → 00F | ε
Derivation Tree/Parse Tree
Generation of Derivation Tree
A derivation tree or parse tree is an ordered rooted tree that graphically represents the
semantic information a string derived from a context-free grammar.
Representation Technique:
1. Root vertex: Must be labeled by the start symbol.
2. Vertex: Labeled by a non-terminal symbol.
3. Leaves: Labeled by a terminal symbol or ε.
If S → x1x2 …… xn is a production rule in a CFG, then the parse tree / derivation tree will
be as follows:
There are two different approaches to draw a derivation tree:
1. Top-down Approach:
(a) Starts with the starting symbol S
(b) Goes down to tree leaves using productions
2. Bottom-up Approach:
(a) Starts from tree leaves
(b) Proceeds upward to the root which is the starting symbol S
Derivation or Yield of a Tree
The derivation or the yield of a parse tree is the final string obtained by concatenating the
labels of the leaves of the tree from left to right, ignoring the Nulls. However, if all the
leaves are Null, derivation is Null.
Example
Let a CFG {N,T,P,S} be
N = {S}, T = {a, b}, Starting symbol = S, P = S → SS | aSb | ε
One derivation from the above CFG is “abaabb”
Answer
S → SS
S → aSbS (replace S →aSb)
S →abS (replace S →ε)
S → abaSb (replace S →aSb)
S → abaaSbb (replace S →aSb)
S→ abaabb (replace S →ε)
Sentential Form and Partial Derivation Tree
A partial derivation tree is a sub-tree of a derivation tree/parse tree such that either all of
its children are in the sub-tree or none of them are in the sub-tree.
Example
If in any CFG the productions are:
S → AB, A → aaA | ε, B →Bb| ε
the partial derivation tree can be the following:
If a partial derivation tree contains the root S, it is called a sentential form. The above
sub-tree is also in sentential form.
Types of Derivation Tree
Leftmost and Rightmost Derivation of a String
1. Leftmost derivation - A leftmost derivation is obtained by applying production to
the leftmost variable in each step.
2. Rightmost derivation - A rightmost derivation is obtained by applying production
to the rightmost variable in each step.
Example
Let any set of production rules in a CFG be
X → X+X | X*X |X| a
over an alphabet {a}.
Find the leftmost derivation for the string
"a+a*a“.
Answer:
X → X+X
X→ a+X
X→ a+ X*X
X→a+a*X
X→ a+a*a
Example
Let any set of production rules in a CFG be
X → X+X | X*X |X| a
over an alphabet {a}.
Find the Rightmost derivation for the string
"a+a*a“.
Answer:
X → X*X
X→ X*a
X → X+X*a
X →X+a*a
X→ a+a*a
Example:
Consider the following grammar
S → bB/Aa
A→b/ bs/ aAA
B → a/ aS/ Bbb
Find:
Leftmost and right most derivation For string baababa and Also find derivation tree
Left and Right Recursive Grammars
In a context-free grammar G, if there is a production in the form X → Xa where X is a non-
terminal and ‘a’ is a string of terminals, it is called a left recursive production. The grammar
having a left recursive production is called a left recursive grammar.
And if in a context-free grammar G, if there is a production is in the form X → aX where X is a
non-terminal and ‘a’ is a string of terminals, it is called a right recursive production. The grammar
having a right recursive production is called a right recursive grammar.
Ambiguity in Context-Free Grammars
If a context free grammar G has more than one derivation tree for some string w ∈ L(G), it is
called an ambiguous grammar. There exist multiple right-most or left-most derivations for some
string generated from that grammar.
Problem
Check whether the grammar G with production rules:
X → X+X | X*X |X| a
is ambiguous or not.
Solution
Let’s find out the derivation tree for the string "a+a*a". It has two derivations.
Derivation 1:
X → X+X
X→ a +X
X→ a+ X*X
X →a+a*X
X→ a+a*a
Parse tree1:
Since there are two parse trees for a single string
"a+a*a", the grammar G is ambiguous
Derivation 2:
X → X*X
X→X+X*X
X→ a+ X*X
X →a+a*X
X→ a+a*a
Parse tree 2:
CFG Simplification
In a CFG, it may happen that all the production rules and symbols are not needed for the
derivation of strings. Besides, there may be some null productions and unit productions.
Elimination of these productions and symbols is called simplification of CFGs.
Simplification essentially comprises of the following steps:
Reduction of CFG
Removal of Unit Productions
Removal of Null Productions
Reduction of CFG
CFGs are reduced in two phases:
Phase 1: Derivation of an equivalent grammar, G’, from the CFG, G, such that each variable
derives some terminal string.
Derivation Procedure:
Step 1: Include all symbols, W1, that derive some terminal and initialize i=1.
Step 2: Include all symbols, Wi+1, that derive Wi.
Step 3: Increment i and repeat Step 2, until Wi+1 = Wi.
Step 4: Include all production rules that have Wi in it.
Phase 2:
Derivation of an equivalent grammar, G”, from the CFG, G’, such that each symbol appears in a
sentential form.
Derivation Procedure:
Step 1: Include the start symbol in Y1 and initialize i = 1.
Step 2: Include all symbols, Yi+1, that can be derived from Yi and include all production rules
that have been applied.
Step 3: Increment i and repeat Step 2, until Yi+1 = Yi.
Problem
Find a reduced grammar equivalent to the grammar G, having production rules,
P: S AC | B, A  a, C  c | BC, E  aA | e
Solution
Phase 1:
T = { a, c, e }
W1 = { A, C, E } from rules A  a, C  c and E  aA
W2 = { A, C, E } U { S } from rule S  AC
W3 = { A, C, E, S } U 
Since W2 = W3, we can derive G’ as:
G’ = { { A, C, E, S }, { a, c, e }, P, {S}}
where P: S  AC, A  a, C  c , E  aA | e
Phase 2:
Y1 = { S }
Y2 = { S, A, C } from rule S  AC
Y3 = { S, A, C, a, c } from rules A  a and C  c
Y4 = { S, A, C, a, c }
Since Y3 = Y4, we can derive G” as:
G” = { { A, C, S }, { a, c }, P, {S}}
where P: S  AC, A  a, C  c
Removal of Unit productions
Any production rule in the form A → B where A, B ∈ Non-terminal is called unit production.
Removal Procedure:
Step 1: To remove A→B, add production A → x to the grammar rule whenever B → x
occurs in the grammar. [x ∈ Terminal, x can be Null]
Step 2: Delete A→B from the grammar.
Step 3: Repeat from step 1 until all unit productions are removed.
Problem
Remove unit production from the following:
S → XY, X → a, Y → Z | b, Z → M, M → N, N → a
Solution:
There are 3 unit productions in the grammar:
Y → Z, Z → M, and M → N
At first, we will remove M → N.
As N → a, we add M → a, and M → N is removed.
The production set becomes
S → XY, X → a, Y → Z | b, Z → M, M → a, N → a
Now we will remove Z → M.
As M → a, we add Z→ a, and Z → M is removed.
The production set becomes
S → XY, X → a, Y → Z | b, Z → a, M → a, N → a
Now we will remove Y → Z.
As Z → a, we add Y→ a, and Y → Z is removed.
The production set becomes
S → XY, X → a, Y → a | b, Z → a, M → a, N → a
Now Z, M, and N are unreachable, hence we can remove those.
The final CFG is unit production free:
S → XY, X → a, Y → a | b
Removal of Null Productions
In a CFG, a non-terminal symbol ‘A’ is a nullable variable if there is a production A → ϵ or
there is a derivation that starts at A and finally ends up with
ϵ: A → .......… → ϵ
Removal Procedure:
Step1 Find out nullable non-terminal variables which derive ϵ.
Step2 For each production A → a, construct all productions A → x where x is obtained
from ‘a’ by removing one or multiple non-terminals from Step 1.
Step3 Combine the original productions with the result of step 2 and remove ϵ-
productions.
Problem
Remove null production from the following:
S→ASA | aB | b, A → B, B → b | ϵ
Solution:
There are two nullable variables: A and B
At first, we will remove B → ϵ.
After removing B → ϵ, the production set becomes:
S→ASA | aB | b | a, A → B| b | ϵ, B → b
Now we will remove A → ϵ.
After removing A → ϵ, the production set becomes:
S→ASA | aB | b | a | SA | AS | S, A → B| b, B → b
This is the final production set without null transition.
Context free grammar

More Related Content

What's hot

Nondeterministic Finite Automata
Nondeterministic Finite AutomataNondeterministic Finite Automata
Nondeterministic Finite AutomataAdel Al-Ofairi
 
NFA to DFA
NFA to DFANFA to DFA
NFA to DFA
Animesh Chaturvedi
 
Introduction TO Finite Automata
Introduction TO Finite AutomataIntroduction TO Finite Automata
Introduction TO Finite Automata
Ratnakar Mikkili
 
Compiler design syntax analysis
Compiler design syntax analysisCompiler design syntax analysis
Compiler design syntax analysis
Richa Sharma
 
Intro automata theory
Intro automata theory Intro automata theory
Intro automata theory
Rajendran
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translation
Akshaya Arunan
 
Automata theory
Automata theoryAutomata theory
Automata theory
Pardeep Vats
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notationsNikhil Sharma
 
pushdown automata
pushdown automatapushdown automata
pushdown automata
Sujata Pardeshi
 
Ll(1) Parser in Compilers
Ll(1) Parser in CompilersLl(1) Parser in Compilers
Ll(1) Parser in Compilers
Mahbubur Rahman
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
Ratnakar Mikkili
 
Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)   Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)
Tasif Tanzim
 
Theory of Automata
Theory of AutomataTheory of Automata
Theory of Automata
Farooq Mian
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
Protap Mondal
 
Regular Grammar
Regular GrammarRegular Grammar
Regular Grammar
Ruchika Sinha
 
Lexical analysis - Compiler Design
Lexical analysis - Compiler DesignLexical analysis - Compiler Design
Lexical analysis - Compiler Design
Muhammed Afsal Villan
 
Push Down Automata (PDA) | TOC (Theory of Computation) | NPDA | DPDA
Push Down Automata (PDA) | TOC  (Theory of Computation) | NPDA | DPDAPush Down Automata (PDA) | TOC  (Theory of Computation) | NPDA | DPDA
Push Down Automata (PDA) | TOC (Theory of Computation) | NPDA | DPDA
Ashish Duggal
 
Decision properties of reular languages
Decision properties of reular languagesDecision properties of reular languages
Decision properties of reular languages
SOMNATHMORE2
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
Dr. C.V. Suresh Babu
 
Turing Machine
Turing MachineTuring Machine
Turing Machine
Rahul Narang
 

What's hot (20)

Nondeterministic Finite Automata
Nondeterministic Finite AutomataNondeterministic Finite Automata
Nondeterministic Finite Automata
 
NFA to DFA
NFA to DFANFA to DFA
NFA to DFA
 
Introduction TO Finite Automata
Introduction TO Finite AutomataIntroduction TO Finite Automata
Introduction TO Finite Automata
 
Compiler design syntax analysis
Compiler design syntax analysisCompiler design syntax analysis
Compiler design syntax analysis
 
Intro automata theory
Intro automata theory Intro automata theory
Intro automata theory
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translation
 
Automata theory
Automata theoryAutomata theory
Automata theory
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
 
pushdown automata
pushdown automatapushdown automata
pushdown automata
 
Ll(1) Parser in Compilers
Ll(1) Parser in CompilersLl(1) Parser in Compilers
Ll(1) Parser in Compilers
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)   Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)
 
Theory of Automata
Theory of AutomataTheory of Automata
Theory of Automata
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
Regular Grammar
Regular GrammarRegular Grammar
Regular Grammar
 
Lexical analysis - Compiler Design
Lexical analysis - Compiler DesignLexical analysis - Compiler Design
Lexical analysis - Compiler Design
 
Push Down Automata (PDA) | TOC (Theory of Computation) | NPDA | DPDA
Push Down Automata (PDA) | TOC  (Theory of Computation) | NPDA | DPDAPush Down Automata (PDA) | TOC  (Theory of Computation) | NPDA | DPDA
Push Down Automata (PDA) | TOC (Theory of Computation) | NPDA | DPDA
 
Decision properties of reular languages
Decision properties of reular languagesDecision properties of reular languages
Decision properties of reular languages
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
 
Turing Machine
Turing MachineTuring Machine
Turing Machine
 

Similar to Context free grammar

Theory of Computation FSM Grammar Minimisation and Normal Forms
Theory of Computation FSM Grammar Minimisation and Normal FormsTheory of Computation FSM Grammar Minimisation and Normal Forms
Theory of Computation FSM Grammar Minimisation and Normal Forms
Rushabh2428
 
Lefmost rightmost TOC.pptx
Lefmost rightmost TOC.pptxLefmost rightmost TOC.pptx
Lefmost rightmost TOC.pptx
Jisock
 
Theory of competition topic simplification of cfg, normal form of FG.pptx
Theory of competition topic simplification of cfg, normal form of FG.pptxTheory of competition topic simplification of cfg, normal form of FG.pptx
Theory of competition topic simplification of cfg, normal form of FG.pptx
Jisock
 
Eliminating ^ production and Unit Production from a CFG.pptx
Eliminating ^ production and Unit Production from a CFG.pptxEliminating ^ production and Unit Production from a CFG.pptx
Eliminating ^ production and Unit Production from a CFG.pptx
SomnathMule5
 
Formal Languages and Automata Theory unit 3
Formal Languages and Automata Theory unit 3Formal Languages and Automata Theory unit 3
Formal Languages and Automata Theory unit 3
Srimatre K
 
Context Free Languages by S.Mandal-1.ppt
Context Free Languages by S.Mandal-1.pptContext Free Languages by S.Mandal-1.ppt
Context Free Languages by S.Mandal-1.ppt
1sonalishipu
 
Theory of Automata and formal languages Unit 3
Theory of Automata and formal languages Unit 3Theory of Automata and formal languages Unit 3
Theory of Automata and formal languages Unit 3
Abhimanyu Mishra
 
Normal Forms for CFG's.pdf
Normal Forms for CFG's.pdfNormal Forms for CFG's.pdf
Normal Forms for CFG's.pdf
Amanda Reznor
 
test pre
test pretest pre
test pre
farazch
 
Automata theory - CFG and normal forms
Automata theory - CFG and normal formsAutomata theory - CFG and normal forms
Automata theory - CFG and normal forms
Akila Krishnamoorthy
 
Calculus- Basics
Calculus- BasicsCalculus- Basics
Calculus- Basics
Rabin BK
 
Ch06
Ch06Ch06
Ch06
Hankyo
 
module4_dynamic programming_2022.pdf
module4_dynamic programming_2022.pdfmodule4_dynamic programming_2022.pdf
module4_dynamic programming_2022.pdf
Shiwani Gupta
 
Mathematics - Functions.pdf
Mathematics - Functions.pdfMathematics - Functions.pdf
Mathematics - Functions.pdf
Jihudumie.Com
 
3.6 applications in optimization
3.6 applications in optimization3.6 applications in optimization
3.6 applications in optimizationmath265
 
2.5 computations of derivatives
2.5 computations of derivatives2.5 computations of derivatives
2.5 computations of derivativesmath265
 
Simplifies and normal forms - Theory of Computation
Simplifies and normal forms - Theory of ComputationSimplifies and normal forms - Theory of Computation
Simplifies and normal forms - Theory of Computation
Nikhil Pandit
 
Note introductions of functions
Note introductions of functionsNote introductions of functions
Note introductions of functions
SMK Tengku Intan Zaharah
 
Introduction to functions
Introduction to functionsIntroduction to functions
Introduction to functions
Elkin Guillen
 

Similar to Context free grammar (20)

Theory of Computation FSM Grammar Minimisation and Normal Forms
Theory of Computation FSM Grammar Minimisation and Normal FormsTheory of Computation FSM Grammar Minimisation and Normal Forms
Theory of Computation FSM Grammar Minimisation and Normal Forms
 
Lefmost rightmost TOC.pptx
Lefmost rightmost TOC.pptxLefmost rightmost TOC.pptx
Lefmost rightmost TOC.pptx
 
Theory of competition topic simplification of cfg, normal form of FG.pptx
Theory of competition topic simplification of cfg, normal form of FG.pptxTheory of competition topic simplification of cfg, normal form of FG.pptx
Theory of competition topic simplification of cfg, normal form of FG.pptx
 
Eliminating ^ production and Unit Production from a CFG.pptx
Eliminating ^ production and Unit Production from a CFG.pptxEliminating ^ production and Unit Production from a CFG.pptx
Eliminating ^ production and Unit Production from a CFG.pptx
 
Formal Languages and Automata Theory unit 3
Formal Languages and Automata Theory unit 3Formal Languages and Automata Theory unit 3
Formal Languages and Automata Theory unit 3
 
Cd2 [autosaved]
Cd2 [autosaved]Cd2 [autosaved]
Cd2 [autosaved]
 
Context Free Languages by S.Mandal-1.ppt
Context Free Languages by S.Mandal-1.pptContext Free Languages by S.Mandal-1.ppt
Context Free Languages by S.Mandal-1.ppt
 
Theory of Automata and formal languages Unit 3
Theory of Automata and formal languages Unit 3Theory of Automata and formal languages Unit 3
Theory of Automata and formal languages Unit 3
 
Normal Forms for CFG's.pdf
Normal Forms for CFG's.pdfNormal Forms for CFG's.pdf
Normal Forms for CFG's.pdf
 
test pre
test pretest pre
test pre
 
Automata theory - CFG and normal forms
Automata theory - CFG and normal formsAutomata theory - CFG and normal forms
Automata theory - CFG and normal forms
 
Calculus- Basics
Calculus- BasicsCalculus- Basics
Calculus- Basics
 
Ch06
Ch06Ch06
Ch06
 
module4_dynamic programming_2022.pdf
module4_dynamic programming_2022.pdfmodule4_dynamic programming_2022.pdf
module4_dynamic programming_2022.pdf
 
Mathematics - Functions.pdf
Mathematics - Functions.pdfMathematics - Functions.pdf
Mathematics - Functions.pdf
 
3.6 applications in optimization
3.6 applications in optimization3.6 applications in optimization
3.6 applications in optimization
 
2.5 computations of derivatives
2.5 computations of derivatives2.5 computations of derivatives
2.5 computations of derivatives
 
Simplifies and normal forms - Theory of Computation
Simplifies and normal forms - Theory of ComputationSimplifies and normal forms - Theory of Computation
Simplifies and normal forms - Theory of Computation
 
Note introductions of functions
Note introductions of functionsNote introductions of functions
Note introductions of functions
 
Introduction to functions
Introduction to functionsIntroduction to functions
Introduction to functions
 

More from Mohammad Ilyas Malik

NLP, Expert system and pattern recognition
NLP, Expert system and pattern recognitionNLP, Expert system and pattern recognition
NLP, Expert system and pattern recognition
Mohammad Ilyas Malik
 
Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)
Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)
Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)
Mohammad Ilyas Malik
 
basic concept of Cloud computing and its architecture
basic concept of Cloud computing  and its architecturebasic concept of Cloud computing  and its architecture
basic concept of Cloud computing and its architecture
Mohammad Ilyas Malik
 
Multimedia communication networks
Multimedia communication networksMultimedia communication networks
Multimedia communication networks
Mohammad Ilyas Malik
 
Virtualization in cloud computing
Virtualization in cloud computingVirtualization in cloud computing
Virtualization in cloud computing
Mohammad Ilyas Malik
 
Seminar report on microsoft azure
Seminar report on microsoft azureSeminar report on microsoft azure
Seminar report on microsoft azure
Mohammad Ilyas Malik
 
Intoduction of cloud computing
Intoduction of cloud computingIntoduction of cloud computing
Intoduction of cloud computing
Mohammad Ilyas Malik
 
Microsoft azure
Microsoft azureMicrosoft azure
Microsoft azure
Mohammad Ilyas Malik
 

More from Mohammad Ilyas Malik (8)

NLP, Expert system and pattern recognition
NLP, Expert system and pattern recognitionNLP, Expert system and pattern recognition
NLP, Expert system and pattern recognition
 
Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)
Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)
Finite Automata: Deterministic And Non-deterministic Finite Automaton (DFA)
 
basic concept of Cloud computing and its architecture
basic concept of Cloud computing  and its architecturebasic concept of Cloud computing  and its architecture
basic concept of Cloud computing and its architecture
 
Multimedia communication networks
Multimedia communication networksMultimedia communication networks
Multimedia communication networks
 
Virtualization in cloud computing
Virtualization in cloud computingVirtualization in cloud computing
Virtualization in cloud computing
 
Seminar report on microsoft azure
Seminar report on microsoft azureSeminar report on microsoft azure
Seminar report on microsoft azure
 
Intoduction of cloud computing
Intoduction of cloud computingIntoduction of cloud computing
Intoduction of cloud computing
 
Microsoft azure
Microsoft azureMicrosoft azure
Microsoft azure
 

Recently uploaded

ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 

Recently uploaded (20)

ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 

Context free grammar

  • 1. Context-Free Grammar Presented by: Mohammad Ilyas Malik M.Tech cse-3rd sem
  • 2. OUTLINE • Context-Free Grammar Introduction • Derivation Tree/Parse Tree • Sentential Form and Partial Derivation Tree • Types of Derivation Tree • Left and Right Recursive Grammars • Ambiguity in Context-Free Grammars • CFG Simplification
  • 3. Context-Free Grammar Introduction Grammar: Grammar is a set of rules which check whether a string belong to a particular language or not. Context-Free Grammar: • It is a notation used to specify the syntax of language. • Context free grammar are used to design parser.
  • 4. Definition: A context-free grammar (CFG) consisting of a finite set of grammar rules is a quadruple (N, T, P, S) where • N is a set of non-terminal symbols. • T is a set of terminals where N ∩ T = NULL. • P is a set of rules, P: N → (N U T)*, i.e., the left-hand side of the production rule P does have any right context or left context. • S is the start symbol. Example • The grammar ({A}, {a, b, c}, P, A), P : A → aA, A → abc. • The grammar ({S, a, b}, {a, b}, P, S), P: S → aSa, S → bSb, S → ε • The grammar ({S, F}, {0, 1}, P, S), P: S → 00S | 11F, F → 00F | ε
  • 5. Derivation Tree/Parse Tree Generation of Derivation Tree A derivation tree or parse tree is an ordered rooted tree that graphically represents the semantic information a string derived from a context-free grammar. Representation Technique: 1. Root vertex: Must be labeled by the start symbol. 2. Vertex: Labeled by a non-terminal symbol. 3. Leaves: Labeled by a terminal symbol or ε.
  • 6. If S → x1x2 …… xn is a production rule in a CFG, then the parse tree / derivation tree will be as follows:
  • 7. There are two different approaches to draw a derivation tree: 1. Top-down Approach: (a) Starts with the starting symbol S (b) Goes down to tree leaves using productions 2. Bottom-up Approach: (a) Starts from tree leaves (b) Proceeds upward to the root which is the starting symbol S
  • 8. Derivation or Yield of a Tree The derivation or the yield of a parse tree is the final string obtained by concatenating the labels of the leaves of the tree from left to right, ignoring the Nulls. However, if all the leaves are Null, derivation is Null.
  • 9. Example Let a CFG {N,T,P,S} be N = {S}, T = {a, b}, Starting symbol = S, P = S → SS | aSb | ε One derivation from the above CFG is “abaabb” Answer S → SS S → aSbS (replace S →aSb) S →abS (replace S →ε) S → abaSb (replace S →aSb) S → abaaSbb (replace S →aSb) S→ abaabb (replace S →ε)
  • 10. Sentential Form and Partial Derivation Tree A partial derivation tree is a sub-tree of a derivation tree/parse tree such that either all of its children are in the sub-tree or none of them are in the sub-tree. Example If in any CFG the productions are: S → AB, A → aaA | ε, B →Bb| ε the partial derivation tree can be the following: If a partial derivation tree contains the root S, it is called a sentential form. The above sub-tree is also in sentential form.
  • 11. Types of Derivation Tree Leftmost and Rightmost Derivation of a String 1. Leftmost derivation - A leftmost derivation is obtained by applying production to the leftmost variable in each step. 2. Rightmost derivation - A rightmost derivation is obtained by applying production to the rightmost variable in each step.
  • 12. Example Let any set of production rules in a CFG be X → X+X | X*X |X| a over an alphabet {a}. Find the leftmost derivation for the string "a+a*a“. Answer: X → X+X X→ a+X X→ a+ X*X X→a+a*X X→ a+a*a
  • 13. Example Let any set of production rules in a CFG be X → X+X | X*X |X| a over an alphabet {a}. Find the Rightmost derivation for the string "a+a*a“. Answer: X → X*X X→ X*a X → X+X*a X →X+a*a X→ a+a*a
  • 14.
  • 15.
  • 16. Example: Consider the following grammar S → bB/Aa A→b/ bs/ aAA B → a/ aS/ Bbb Find: Leftmost and right most derivation For string baababa and Also find derivation tree
  • 17.
  • 18. Left and Right Recursive Grammars In a context-free grammar G, if there is a production in the form X → Xa where X is a non- terminal and ‘a’ is a string of terminals, it is called a left recursive production. The grammar having a left recursive production is called a left recursive grammar. And if in a context-free grammar G, if there is a production is in the form X → aX where X is a non-terminal and ‘a’ is a string of terminals, it is called a right recursive production. The grammar having a right recursive production is called a right recursive grammar.
  • 19. Ambiguity in Context-Free Grammars If a context free grammar G has more than one derivation tree for some string w ∈ L(G), it is called an ambiguous grammar. There exist multiple right-most or left-most derivations for some string generated from that grammar. Problem Check whether the grammar G with production rules: X → X+X | X*X |X| a is ambiguous or not. Solution Let’s find out the derivation tree for the string "a+a*a". It has two derivations.
  • 20. Derivation 1: X → X+X X→ a +X X→ a+ X*X X →a+a*X X→ a+a*a Parse tree1: Since there are two parse trees for a single string "a+a*a", the grammar G is ambiguous Derivation 2: X → X*X X→X+X*X X→ a+ X*X X →a+a*X X→ a+a*a Parse tree 2:
  • 21. CFG Simplification In a CFG, it may happen that all the production rules and symbols are not needed for the derivation of strings. Besides, there may be some null productions and unit productions. Elimination of these productions and symbols is called simplification of CFGs. Simplification essentially comprises of the following steps: Reduction of CFG Removal of Unit Productions Removal of Null Productions
  • 22. Reduction of CFG CFGs are reduced in two phases: Phase 1: Derivation of an equivalent grammar, G’, from the CFG, G, such that each variable derives some terminal string. Derivation Procedure: Step 1: Include all symbols, W1, that derive some terminal and initialize i=1. Step 2: Include all symbols, Wi+1, that derive Wi. Step 3: Increment i and repeat Step 2, until Wi+1 = Wi. Step 4: Include all production rules that have Wi in it.
  • 23. Phase 2: Derivation of an equivalent grammar, G”, from the CFG, G’, such that each symbol appears in a sentential form. Derivation Procedure: Step 1: Include the start symbol in Y1 and initialize i = 1. Step 2: Include all symbols, Yi+1, that can be derived from Yi and include all production rules that have been applied. Step 3: Increment i and repeat Step 2, until Yi+1 = Yi.
  • 24. Problem Find a reduced grammar equivalent to the grammar G, having production rules, P: S AC | B, A  a, C  c | BC, E  aA | e Solution Phase 1: T = { a, c, e } W1 = { A, C, E } from rules A  a, C  c and E  aA W2 = { A, C, E } U { S } from rule S  AC W3 = { A, C, E, S } U  Since W2 = W3, we can derive G’ as: G’ = { { A, C, E, S }, { a, c, e }, P, {S}} where P: S  AC, A  a, C  c , E  aA | e
  • 25. Phase 2: Y1 = { S } Y2 = { S, A, C } from rule S  AC Y3 = { S, A, C, a, c } from rules A  a and C  c Y4 = { S, A, C, a, c } Since Y3 = Y4, we can derive G” as: G” = { { A, C, S }, { a, c }, P, {S}} where P: S  AC, A  a, C  c
  • 26. Removal of Unit productions Any production rule in the form A → B where A, B ∈ Non-terminal is called unit production. Removal Procedure: Step 1: To remove A→B, add production A → x to the grammar rule whenever B → x occurs in the grammar. [x ∈ Terminal, x can be Null] Step 2: Delete A→B from the grammar. Step 3: Repeat from step 1 until all unit productions are removed.
  • 27. Problem Remove unit production from the following: S → XY, X → a, Y → Z | b, Z → M, M → N, N → a Solution: There are 3 unit productions in the grammar: Y → Z, Z → M, and M → N At first, we will remove M → N. As N → a, we add M → a, and M → N is removed. The production set becomes S → XY, X → a, Y → Z | b, Z → M, M → a, N → a Now we will remove Z → M. As M → a, we add Z→ a, and Z → M is removed. The production set becomes S → XY, X → a, Y → Z | b, Z → a, M → a, N → a
  • 28. Now we will remove Y → Z. As Z → a, we add Y→ a, and Y → Z is removed. The production set becomes S → XY, X → a, Y → a | b, Z → a, M → a, N → a Now Z, M, and N are unreachable, hence we can remove those. The final CFG is unit production free: S → XY, X → a, Y → a | b
  • 29. Removal of Null Productions In a CFG, a non-terminal symbol ‘A’ is a nullable variable if there is a production A → ϵ or there is a derivation that starts at A and finally ends up with ϵ: A → .......… → ϵ Removal Procedure: Step1 Find out nullable non-terminal variables which derive ϵ. Step2 For each production A → a, construct all productions A → x where x is obtained from ‘a’ by removing one or multiple non-terminals from Step 1. Step3 Combine the original productions with the result of step 2 and remove ϵ- productions.
  • 30. Problem Remove null production from the following: S→ASA | aB | b, A → B, B → b | ϵ Solution: There are two nullable variables: A and B At first, we will remove B → ϵ. After removing B → ϵ, the production set becomes: S→ASA | aB | b | a, A → B| b | ϵ, B → b Now we will remove A → ϵ. After removing A → ϵ, the production set becomes: S→ASA | aB | b | a | SA | AS | S, A → B| b, B → b This is the final production set without null transition.