1

I'm not sure if there is some library that handles this, or if recursion is the way to go. I am trying to write a recursion function, when I call it it always ends up returning False. Any help appreciated.

item starts out as a dict. text is a string to match.

def match(item, text):
    if item == text:
        return True
    if type(item) == list:
        for i in item:
            match(i, text)
    if type(item) == dict:
        for i in item.values():
             match(i text)
    return False

I'm not quite grasping how to have it keep going when say the first item of a list is not a match.

chrismint
  • 47
  • 1
  • 6

1 Answers1

4

You're not returning True when the recursive call finds a match.

def match(item, text):
    if item == text:
        return True
    if isinstance(item, (list, tuple)):
        return any(match(i, text) for i in item)
    if isinstance(item, dict):
        return any(match(i, text) for i in item.values())
    return False

You should also use isinstance() for type checks, to allow for subclasses.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I am out of close votes today, but you should know well by now that this is a common duplicate: the canonical is [Why does my recursive function return None?](https://stackoverflow.com/questions/17778372). – Karl Knechtel Mar 03 '23 at 18:20
  • @KarlKnechtel No, it's not as simple as the usual `return recursive_call(...)`, because additional logic is needed with the result of the recursive calls. – Barmar Mar 03 '23 at 18:23
  • Aside from the part where you know that a question with multiple problems is too broad, we have canonicals for that, too. – Karl Knechtel Mar 03 '23 at 18:27