This project implements a parser for a Context-Free Grammar (CFG), performs derivations, generates strings, and tests string membership for a given CFG.
The Python script CFG.py addresses the following tasks as outlined in the assignment:
- Define a CFG: Programmatic representation of a CFG.
- String Generator: A function to randomly generate strings from the defined CFG.
- Derivation: A function to display the derivation of a target string. (Leftmost Derivation)
- Membership Tester: A recognizer function to check if a given string belongs to the language of the CFG.
The implemented CFG is based on the example
-
Non-Terminals (V):
{S} -
Terminals (
$\Sigma$ ):{a, b} -
Production Rules (R):
S -> aSb-
S ->(epsilon, represented as an empty string''in the code)
-
Start Symbol (S):
S
This definition is programmatically represented in the CFG.py script.
- Ensure you have Python installed on your system.
- Save the provided code as
CFG.py. - Open a terminal or command prompt.
- Navigate to the directory where you saved
CFG.py. - Run the script using the command:
python3 CFG.py
The script will execute and print the outputs for each task directly to the console.
The script will output:
- The definition of the CFG (Non-terminals, Terminals, Production Rules, Start Symbol).
- Up to 10 randomly generated strings from the CFG, each with a maximum length of 10 characters.
- Derivation steps for predefined test strings (e.g., "aabb", "aaabbb", "ab", "", "aab").
- Membership test results (True/False) for a list of predefined test strings (e.g., "aabb", "ab", "", "aaabbb", "aab", "aba").