Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Python Problem: - Expression Trees During lecture, we saw a way to represent arithmetic expressions with variables, as follows: A number is represented as a
Python Problem:
- Expression Trees During lecture, we saw a way to represent arithmetic expressions with variables, as follows: A number is represented as a Python number. A variable is represented as a Python string. A composite expression (ei tea) is represented as a three-element Python tuple ('+', e_1, e_2), where e_1 and e_2 are the Python representations of ei and e2, respectively. We do the analogous thing for , X, and = operations, for which we will use '-','*', and 7 as the first element in the tuple. For example, we represent the expression 3 : 4 as the tuple ('7', 3, 4) and the expression 2 x (x+1) as the Python tuple ("*', 2, ('+', 'x', 1)). Problem 1: Finding the set of variables appearing in an expression For this problem, you will write a function variables that takes an expression, as defined above, and returns the set of variables in that expression, represented as a Python set. Here are several examples: For the expression ('*', 2, ('+', 'x', 1)), variables should return {'x'}. For the expression 'x', variables should return {'x'). For the expression 3, variables should return set (the empty set in Python). For the expression ('7', 'a', ('7', 'b', ('7', 'c', 'd'))), variables should return {'a', 'b', 'c': 'd'}. For the expression ('7', 3, 4), variables should return set(). The test cases below contain some more example inputs and outputs. Hint: You can solve this problem by writing a recursive function with numbers and variables as the base cases, and composite expressions as the recursive case. In the recursive case, find the set of variables in each subexpression and then combine them using the appropriate operation. (See the lecture notebook for several examples of recursive functions that operate on expression trees.) [ ] # In this problem and in the following problems, # You can check if an expression e is a number # by checking if 'isinstance(e, Number)' evaluates to True. from numbers import Number def variables(e): """Takes an expression and returns the set of variables appearing in the expression, represented as a Python set. It can be done in less than 8 lines of code.""" # YOUR CODE HERE raise NotImplementedError()Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started