Docsity

Algorithm analysis Design and Microprocessor - Context-Free Languages, Study notes of Design and Analysis of Algorithms

Partial preview of the text

Download Algorithm analysis Design and Microprocessor - Context-Free Languages and more Study notes Design and Analysis of Algorithms in PDF only on Docsity!

Context-Free Languages

• Not all languages are regular.

• L 1 = {anbn^ | n  0} is not regular.

L 2 = {(), (()), ((())), ...} is not regular.

some properties of programming languages

Context-Free Grammars

G = (V, T, S, P)

Productions are of the form:

A  x

A  V and x  (V  T)*

Context-Free Grammars

• A regular language is also a context-free

language.

• Why the name?

Example

  • (^) G = ({S}, {a, b}, S, P) P = { S  aSa S  bSb S   } S  aSa  aaSaa  aabSbaa  aabbaa

Example

  • (^) G = ({S, A, B}, {a, b}, S, P) P = { S  abB A  aaBb B  bbAa A   } S  abB  abbbAa  abbbaaBba  abbbaabbAaba  abbbaabbaba

Example

  • (^) L = {anbm^ | n  m} is context-free. G = (?, {a, b}, S, ?)

Example

  • (^) G = ({S}, {a, b}, S, P) P = { S  aSb | SS | } S  aSb  aaSbb  aaSSbb  aaabSbb  aaababbb

Example

  • (^) G = ({S}, {a, b}, S, P) P = { S  aSb | SS | } S  aSb  aaSbb  aaSSbb  aaabSbb  aaababbb L(G) =?

Derivations

• Leftmost: in each step the leftmost variable in the

sentential form is replaced.

• Rightmost: in each step the rightmost variable in

the sentential form is replaced.

Example

  • (^) G = ({S, A, B}, {a, b}, S, {S  AB, A  aaA, A  , B  Bb, B  }) 1 2 3 4 5 S  AB  aaAB  aaB  aaBb  aab leftmost S  AB  ABb  aaABb  aaAb  aab 1 2 3 4 5 1 4 2 5 3

Derivation Trees

  • (^) Let G = (V, T, S, P) be a context-free grammar. An ordered tree is a derivation tree iff: 1. The root is labeled S. 2. Every leaf has a label from T  {}. 3. Every interior vertex has a label from V. 4. A vertex has label AV and its children are labeled a 1 , a 2 , ..., an iff P contains the production A  a 1 a 2 ... an. 5. A leaf labeled  has no siblings.

Derivation Trees

  • (^) Let G = (V, T, S, P) be a context-free grammar. An ordered tree is a partial derivation tree iff: 1. The root is labeled S. 2. Every leaf has a label from T  {}. Every leaf has a label from V  T  {}. 1. Every interior vertex has a label from V. 2. A vertex has label AV and its children are labeled a 1 , a 2 , ..., an iff P contains the production A  a 1 a 2 ... an. 5. A leaf labeled  has no siblings.

Derivation Trees

S  aAB A  bBb B  A |  yield: abbbb

S

b a B b

A

B

b b

A

B

Derivation Trees

S  aAB A  bBb B  A | 

S

b a B b

A

B

b b

A

B

partial derivation tree