use python3 programming language Write a program that executes the Parse algorithm for…
- User
use python3 programming language Write a program that executes the Parse algorithm for the grammar and table (1) below. The program receives a sequence of tokens from user input (only one command from the input like d+d*d) and run parse LL1 on it. If the input string is correct, the program should also display the desired derivation. You have to give the table to the program in a fixed way.
- E -> TE' 2,3) E' -> +TE'|λ
- T -> FT' 5,6) T' -> *FT'|λ 7,8) F -> (E)|d
+-------+-----+-----+-----+-----+-----+-----+ | | d | + | * | ( | ) | $ | +-------+-----+-----+-----+-----+-----+-----+ | E | 1 | | | 1 | | | +-------+-----+-----+-----+-----+-----+-----+ | E' | | 2 | | | 3 | 3 | +-------+-----+-----+-----+-----+-----+-----+ | T | 4 | | | 4 | | | +-------+-----+-----+-----+-----+-----+-----+ | T' | | 6 | 5 | | 6 | 6 | +-------+-----+-----+-----+-----+-----+-----+ | F | 8 | | | 7 | | | +-------+-----+-----+-----+-----+-----+-----+
- Assistant
Here is the code for parsing algorithm:
def parse(tokens): tokens = list(tokens + "$") symbol = ['E', 'E\'', 'T', 'T\'', 'F'] ll1_table = { ('E', 'd'): '1', ('E', '('): '1', ('E\'', '+'): '2', ('E\'', ')'): '3', ('E\'', '$'): '3', ('T', 'd'): '4', ('T', '('): '4', ('T\'', '+'): '6', ('T\'', '*'): '5', ('T\'', ')'): '6', ('T\'', '$'): '6', ('F', 'd'): '8', ('F', '('): '7' } grammar = { '1': ["E -> TE'"], '2': ["E' -> +TE'"], '3': ["E' -> λ"], '4': ["T -> FT'"], '5': ["T' -> *FT'"], '6': ["T' -> λ"], '7': ["F -> (E)"], '8': ["F -> d"] } stack = ['$','E'] derivation = [] while len(stack) > 0: if tokens and stack: top = stack.pop() current_input = tokens[0] if top in symbol: pair = (top, current_input) if pair in ll1_table: rule_number = ll1_table[pair] derivation.append(grammar[rule_number][0]) rule = grammar[rule_number][0].split(" -> ")[1].replace("λ", "") if rule: stack.extend(reversed(rule.split())) elif top == current_input: tokens.pop(0) else: return False elif top == current_input: tokens.pop(0) else: return False return derivation if __name__ == "__main__": user_input = input("Enter a sequence of tokens: ") result = parse(user_input) if result: print("\nThe input string is correct.") print("\nThe derivation:") for item in result: print(item) else: print("\nThe input string is incorrect.")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.