Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context free grammar for languages with more number of as than bs

The question is to develop a context free grammar for language containing all strings having more number of As than Bs.

I can't think of a logical solution . Is there a way to approach such problems , what can help me approach such problems better ? Can someone suggest a logical way to analyse such grammar problems ?

like image 821
nino Avatar asked Apr 01 '16 15:04

nino


People also ask

Can context-free languages be infinite?

Proof: (1) There are a countably infinite number of context-free languages. This true because every description of a context-free language is of finite length, so there are a countably infinite number of such descriptions. (2) There are an uncountable number of languages.

What is context-free language give example?

In formal language theory, a context-free language (CFL) is a language generated by a context-free grammar (CFG). Context-free languages have many applications in programming languages, in particular, most arithmetic expressions are generated by context-free grammars.

Can a language have more than one grammar?

For a given language L(G), there can be more than one grammar which can produce L(G).

Is a Nb N context-free?

Example 1: L1 = { anbn | n is a positive integer } is a context-free language. For the following context-free grammar G1 = < V1 , , S , P1 > generates L1 : V1 = { S } , = { a , b } and P1 = { S -> aSb , S -> ab }.


1 Answers

The following grammar generates all strings over {a,b} that have more a's than b's. I denote by eps the empty string.

S -> Aa | RS | SRA
A -> Aa | eps
R -> RR | aRb | bRa | eps

It's obvious it always generates more a's than b's. It's less obvious it generates all possible strings over {a,b} that have more a's than b's

The production R -> RR | aRb | bRa | eps generates all balanced strings (this is easy to see), and the production A -> Aa generates the language a* (i.e. strings with zero or more a's).

Here's the logic behind the grammar. Notice that if w=c1,c2,c3,...,cn is a string over {a,b} with more a's than b's then we can always decompose it into a concatenation of balanced strings (i.e. equal number of a's and b's, which includes the empty string) and strings of the form a+.

For example, ababaaaba = abab (can be generated by R),aaa (can be generated by A),ba (can be generated by R).

Now notice that the production S -> Aa | RS | SRA generates precisely strings of this form.

It suffices to verify that S covers the following cases (because every other case can be covered by breaking into such subcases, as you should verify):

  • [a][balanced]: use S => SRA => AaR.
  • [balanced][a]: use S => RS => RA => RAa.
  • [balanced][a]balanced]: use S => SRA => RSRA => RAaR.
like image 182
blazs Avatar answered Sep 30 '22 09:09

blazs