CoolKid
CoolKid

Reputation: 143

How to recursively implement the following method about nested list?

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]

Upvotes: 0

Views: 173

Answers (1)

Blckknght
Blckknght

Reputation: 104712

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

Upvotes: 2

Related Questions