Python return statement not returning correct output

Question:

I have a simple function to return True or False when a condition is met. But the return statement is not functioning as I expected. Could anyone help me out to point out the mistake I am making.

graph = {
'f': ['g', 'i'],
'g': ['h'],
'h': [],
'i': ['g', 'k'],
'j': ['i'],
'k': []
}

def hasPath(graph,source,des):
    arr = graph[source]
    if des in arr:
        print('Yes')
        return True
    for i in arr:
        hasPath(graph,i,des)
    return False

print(hasPath(graph,'f','k'))

This code return False but prints the statment Yes. I am not sure why return statement is not being executed after the Print statement.

Asked By: Tushar Sethi

||

Answers:

In the hasPath function, you are calling the function recursively on each element in the arr list, and the return value of the recursive calls is not being used. This means that even if the des value is present in the arr list and the print statement is executed, the return False statement at the end of the function will still be executed and the False value will be returned.

To fix this issue, you can add a return statement after the recursive call to hasPath to return the value of the recursive call. This will ensure that the return True statement is executed when the des value is found in the arr list, and the return False statement at the end of the function will not be executed.

Here is an example of how you can modify the hasPath function to fix this issue:

def hasPath(graph, source, des):
    arr = graph[source]
    if des in arr:
        print('Yes')
        return True
    for i in arr:
        if hasPath(graph, i, des):
            return True
    return False

With this change, the hasPath function will return True when the des value is found in the arr list, and will return False otherwise. When you run the print(hasPath(graph, 'f', 'k')) statement, it will print Yes and then True, as expected.

Answered By: Agni

Try this:

graph = {
'f': ['g', 'i'],
'g': ['h'],
'h': [],
'i': ['g', 'k'],
'j': ['i'],
'k': []
}

def hasPath(graph,source,des):
    arr = graph[source]
    if des in arr:
        print('Yes')
        return True
    for i in arr:
        if hasPath(graph,i,des): return True
    return False

print(hasPath(graph,'f','k'))

Result:

Yes
True

Why?

Well try to look at each iteration:

  1. source is f, arr = [‘g’, ‘i’] = False
  2. source changes to i = g, now arr = [‘h’] = False
  3. source changes to h which is empty and returns False
  4. First iteration changes to i in graph[f] and it starts again
  5. Source changes to g in key i = False
  6. source changes to k in key i = True
Answered By: user56700
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.