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.

Nathan Vērzemnieks
  • 5,495
  • 1
  • 11
  • 23
shindeiru
  • 169
  • 9

1 Answers1

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
trincot
  • 317,000
  • 35
  • 244
  • 286