0

I was trying to write a function that takes a list and and an element as input and returns it's deepness. If the element is not found, returns -1

def find_e(l, e):
    for i in l:
        if isinstance(i, list):
            return find_e(i, e) + 1
        if i == e:
            return 1
        else:
            return -1

For inputs

[[1, 9], 0, [[[["a"]]]]], "a"
[[1, 9], 0, [[[["a"]]]]], "b"

It should return 5 and -1, but this clearly doesn't work.

0

1 Answer 1

2

This fails because:

  • you don't check whether the recursive call returned -1. In that case you should return -1 again, not add 1 to it.

  • you should only return -1 after having gone through all iterations of the loop, as there might still be a match later. In fact, in your code, the loop always exits in the first iteration.

Corrected version:

def find_e(l, e):
    for i in l:
        if isinstance(i, list):
            res = find_e(i, e)
            if res >= 0:
                return res + 1
        if i == e:
            return 1
    return -1
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.