简体   繁体   中英

checking if the graph is bipartite.why is my function returning none?

import collections
class Solution(object):
    def possibleBipartition(self, N, dislikes):
        graph = collections.defaultdict(list)
        for u, v in dislikes:
            graph[u].append(v)
            graph[v].append(u)

        color = {}
        def dfs(node, c = 0):
            if node in color:
                return color[node] == c
            color[node] = c
            for nei in graph[node]:
                dfs(nei,c^1)

        for node in range(1, N+1):
            if node not in color:
                dfs(node)
g=Solution()
N=3
dislikes=[[1,2],[2,3]]
print(g.possibleBipartition(N, dislikes))

Numerous solution is available online.But I am new to recursion. I want to understand why is my function returning none as the knowledge is going to help me later:) Thanks in advance.

Seems it's returning None since you don't have a return... anywhere in your code. I'd make sure that you're explicitly returning where you need to be. For example, two spots that you might want to add a return statement:

return dfs(nei,c^1)

in your dfs() function as well as:

return dfs(node)

in your possibleBipartition() function.

Note that you need to explicitly specify the return in Python if there is one unlike in languages like Racket and Haskell.

On the surface, the function returns None because you have no return statement. So the function possibleBipartition doesn't return anything (ie None). This is just a syntax thing that python allows you to do without any error, which can be confusing to new people. You're going to need to return something from your function in order for your print statement to not just print None . A good idea might be to return True if and only if the possibleBipartition is valid.

One adjustment you could play with is checking the color dict you build in the function to see if the "possibleBipartition" is valid or not. This can be achieved knowing the following fact: A graph has a valid biparitition iff each vertex is only belongs to one color (0 or 1 in your case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM