skip to Main Content

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


  1. 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:

    lorenzo@pc:~$ python
    Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
    [GCC 4.8.4] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 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
    ... 
    >>> depth([['expt', 'x', 2]])
    True
    False
    False
    False
    1
    

    I suspect you are calling it with depth(['expt', 'x', 2]) which gives

    >>> depth(['expt', 'x', 2])
    False
    False
    False
    0
    
    Login or Signup to reply.
  2. Look at your code:

    def depth(expr):
        d = 0
        for item in expr:
    

    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 start d at 1, not 0.

    Otherwise, you might test expr to see whether it’s a list/tuple; if not, return 0; if so, start d at 1 and loop through the elements (current loop logic).

    Does that disambiguate your base case?

    Try this introduction to the routine:

    def depth(expr):
        if isinstance(item, (tuple, list)):
            d = 1
            for item in expr:
                lvl = 1 + depth(item)
                if lvl >= d:
                    d = lvl
        else:
            d = 0
    return d
    

    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).

    Login or Signup to reply.
  3. After looking at the assignment and the tests.py file, I’m pretty sure it’s calling your function with

    apply(depth, depth_2_getargs())
    

    rather than passing the result of depth_2_getargs() as a single argument. That’s why it’s called getargs instead of getarg. (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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search