I am new to python and am taking the artificial intelligence course on MIT OpenCourseWare. I am working on the lab0 assignment, “Expression Depth” question for reference.
When I run my code, it is not taking the first item
in the expr
as a list even when it is, so the return value is 1 less than expected.
Code:
def depth(expr):
d = 0
for item in expr:
print isinstance(item, (tuple, list))
if isinstance(item, (tuple, list)):
lvl = 1 + depth(item)
if lvl >= d:
d = lvl
return d
A test is run with this argument:
def depth_2_getargs():
return [['expt', 'x', 2]]
the answer here should be d = 1
, but here is my output:
False
False
False
Test 10/23: Incorrect.
depth_2
Got: 0
Expected: 1
So my personal interpretation is that, isinstance(item, (tuple, list))
doesn’t see the first element in expr
as a list, rather item
seems to have taken the first element in the sublist. The output should be
True
False
False
False
Right? The initial True
is from the supplied list; the three False
lines are from iterating on the list elements.
Why does this happen, and how do I fix this?
EDIT: To clarify and save others trouble, the assignment states:
depth('x') => 0
depth(('expt', 'x', 2)) => 1
depth(('+', ('expt', 'x', 2), ('expt', 'y', 2))) => 2
depth(('/', ('expt', 'x', 5), ('expt', ('-', ('expt', 'x', 2), 1), ('/', 5, 2)))) => 4
3
Answers
Maybe when they write return
[['expt', 'x', 2]]
they return a list of all the arguments to pass to your function, whish is only 1 in this case, so the argument they intend to pass is['expt', 'x', 2]
and not['expt', 'x', 2]
Actually the output seems fine to me:
I suspect you are calling it with
depth(['expt', 'x', 2])
which givesLook at your code:
You assume that the given argument is an iterable of some sort (implied in the
for
statement), and you assign the default depth of that sequence as 0. You got exactly what you programmed. If a list is supposed to have an initial depth of 1, then startd
at 1, not 0.Otherwise, you might test
expr
to see whether it’s a list/tuple; if not, return 0; if so, startd
at 1 and loop through the elements (current loop logic).Does that disambiguate your base case?
Try this introduction to the routine:
This defers the base case to receiving a scalar (or string, etc.), which does have a depth of 0. It also returns 1 for the depth of an empty list (which has no items through which to iterate).
After looking at the assignment and the
tests.py
file, I’m pretty sure it’s calling your function withrather than passing the result of
depth_2_getargs()
as a single argument. That’s why it’s calledgetargs
instead ofgetarg
. (apply
is the old way of doing*
and**
arguments.)The assignment states that an input like
['x']
should produce a result of 1, not 0. Your results are off by one. Also, you’re not handling the case where the input isn’t a list or tuple.