0

Here we are trying to generate a new list containing elements from obj if the elements have length greater than n. My code did not pass the doctest as it fails on list_over("five", 3); its prints "[]" when It should print "[five]". However the doctest passed on other docstring examples. But I have a hard time correcting it. Could someone help?

def list_over(obj, n):
    """
    Return a list of strings of length greater than n in obj, or sublists of obj, if obj
    is a list.  Otherwise, if obj is a string return a list containing obj if obj has
    length greater than n, otherwise an empty list.

    @param str|list obj: possibly nested list of strings, or string
    @param int n: non-negative integer
    @rtype: list[str]

    >>> list_over("five", 3)
    ['five']
    >>> list_over("five", 4)
    []
    >>> L = list_over(["one", "two", "three", "four"], 3)
    >>> all([x in L for x in ["three", "four"]])
    True
    >>> all([x in ["three", "four"] for x in L])
    True
    """

    return [list_over(x, n) if isinstance(x,list) else x for x in obj  if len(x)>n]
2
  • 1
    As a start, I'd recommend breaking your very complicated list comprehension down into a line by line logic flow and see if it behaves the same way. When you restructure your code that way, you can add in print lines to debug your code and make sure each step is doing what you want it to do. You can recombine it back into a comprehension at the end. Commented Mar 3, 2016 at 2:52
  • It's not clear from the docstring if the function is supposed to flatten a nested list or not. In my answer, I assumed that it is, but that might not be correct (it's not covered by any of the doctests). Commented Mar 3, 2016 at 2:55

1 Answer 1

2

I don't think you should be trying to wedge the somewhat complex logic of that function into a list comprehension. There are cases you're getting wrong (like more deeply nested lists, and lists with fewer than n members).

Instead, I suggest writing out a function that handles the base case where obj is a string, and the recursive case where it is not:

def list_over(obj, n):
    if isinstance(obj, str): # base case
        if len(obj) > n:
            return [obj]
        else:
            return []

    result = []
    for item in obj:
        result.extend(list_over(item, n)) # recursive case
    return result
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.