Python recursion, how come my function doesn't work? -
i trying write python 3 recursive function tell me if integer in nested list. not sure how can make code return true if finds in list, , false if doesn't find in list. when print result of loop, bunch of
false false false false true false false false etc. but, returns false because last call false, though want return true. how can fix this?
here code:
def nestedlistcontains(nl, target): if( isinstance(nl, int) ): return nl in range(0, len(nl)): return ( nestedlistcontains(nl[i], target) == target ) return false and here how i'm calling it
print(nestedlistcontains([[3], [4,5,7], [[[8]]]], 8)) edit: seems working me, seems rather ghetto:
def nestedlistcontains(nl, target): if( isinstance(nl, int) ): if( nl == target ): return 1 return 0 x = 0 n in nl: x += nestedlistcontains(n, target) == 1 return x != 0
you return result regardless of whether it's true or not. this:
def nestedlistcontains(nl, target): if isinstance(nl, int): return nl == target n in nl: result = nestedlistcontains(n, target) if result: return result return false
Comments
Post a Comment