Explain ambiguous and unambiguous context free grammar with example.
Question
Explain ambiguous and unambiguous context free grammar with example.
Solution
Sure, let's start with the definitions:
- Ambiguous Context Free Grammar: A context free grammar is said to be ambiguous if there exists a string that can be derived in more than one way i.e., the string has more than one parse tree or leftmost derivation.
Example: Consider the grammar G = ({S}, {a, b}, P, S) where P is the set of productions given by:
S -> SS | aSb | ε
The string "aabb" can be derived in two different ways:
- S -> SS -> aSbS -> aSb -> aaSbb -> aabb
- S -> SS -> SaSb -> aaSbb -> aabb
So, this grammar is ambiguous.
- Unambiguous Context Free Grammar: A context free grammar is said to be unambiguous if there exists only one parse tree or leftmost derivation for any string derived from the grammar.
Example: Consider the grammar G = ({S}, {a, b}, P, S) where P is the set of productions given by:
S -> aSb | ε
The string "aabb" can be derived in only one way:
- S -> aSb -> aaSbb -> aabb
So, this grammar is unambiguous.
In summary, the difference between ambiguous and unambiguous context free grammar lies in the number of parse trees or leftmost derivations a string can have. If a string derived from the grammar can have more than one parse tree or leftmost derivation, the grammar is ambiguous. If a string can have only one parse tree or leftmost derivation, the grammar is unambiguous.
Similar Questions
Ambiguous grammar is context free?
Define Ambiguous gramma
A grammar that produces more than one parse tree for some sentence iscalled ____ a) Ambiguous b) Unambiguous c) Regular d) None of the mentioned
Select the correct definition for "ambiguous":*Clear and straightforwardHappy and excitedVague and unclear
what is grammar ? compare descriptive grammar with prescriptive grammar explain with examples
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.