Jeff H.
asked 12/13/19write a program that parses the testProgram string and any other programs that has functions calling each other. The program needs to print out
write a program that parses the testProgram string and any other programs that has functions calling each other. The program needs to print out:
- A Python Dictionary with key:value pairs where the key is the name of a function, and the value is a list of the functions being called by that function. So, for testProgram, the dictionary would look like: { “myF”: [ ‘funF1’. ‘funF2’, ‘funF3’ ]. “funF1”: [], “funF2”: [ ‘funF3’, ‘funF2’], ‘funF3’: [‘funF2’, ‘funF1’’] }
- A list of tuples with the name and the number of statements in each program. For this test, the statements are terminated by ‘;’, a program begins with ‘{‘ and end with ‘}’
So, testProgram would have [(‘myF’, 7), (‘funF1’, 1), (‘funF2’, 3), (‘funF3’, 1)]
1 Expert Answer
def parse_program(program: str):
# Step 1. Find all functions and their bodies
func_pattern = re.compile(r'(\w+)\s*\{([^}]*)\}')
functions = func_pattern.findall(program)
func_calls = {}
stmt_counts = []
# Step 2. For each function body, parse statements and calls
for func_name, body in functions:
# Split by ';' to count statements
statements = [s.strip() for s in body.split(';') if s.strip()]
stmt_counts.append((func_name, len(statements)))
# Find calls to any function name (assuming same naming rule)
calls = re.findall(r'\b\w+\s*\(', body)
# Clean parentheses and remove self calls if desired
calls = [c.strip().rstrip('(').strip() for c in calls if c.strip().rstrip('(') != func_name]
func_calls[func_name] = calls
return func_calls, stmt_counts
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Brian Z.
Can you give more details about your problem, and all testProgram string?12/16/19