Use the function given below to, first, help you to convert a multiline CFG string representation of the form expected into a dictionary represention. Then write the function being asked. def cfg_str_to_dict(cfg_str): """Converts a multiline CFG string representation of the form required into a dictionary represention, e.g. "S=ab|bA|BB|_" becomes {"S": ["ab", "bA", "BB", ""]} """ nonterminals = {char for char in cfg_str if char.isupper()}.union({'S'}) result = {nt: [] for nt in nonterminals} productions = cfg_str.splitlines() for production in productions: nt, rhs = production.split("=") rhs = rhs.replace("_", "") # Use "" for epsilon rhs_list = rhs.split("|") result[nt] = result.get(nt) + rhs_list return result
Use the function given below to, first, help you to convert a multiline CFG string representation of the form expected into a dictionary represention. Then write the function being asked.
def cfg_str_to_dict(cfg_str):
"""Converts a multiline CFG string representation
of the form required into a dictionary represention, e.g.
"S=ab|bA|BB|_" becomes {"S": ["ab", "bA", "BB", ""]}
"""
nonterminals = {char for char in cfg_str if char.isupper()}.union({'S'})
result = {nt: [] for nt in nonterminals}
productions = cfg_str.splitlines()
for production in productions:
nt, rhs = production.split("=")
rhs = rhs.replace("_", "") # Use "" for epsilon
rhs_list = rhs.split("|")
result[nt] = result.get(nt) + rhs_list
return result
Step by step
Solved in 3 steps with 1 images