检查图形是否为bipartite。为什么我的函数不返回任何内容?

时间:2020-05-29 20:11:23

标签: python recursion graph depth-first-search

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))

许多解决方案都可以在线获得。但是我是递归的新手。我想了解为什么我的函数不返回任何内容,因为以后的知识将对我有所帮助:) 预先感谢。

2 个答案:

答案 0 :(得分:0)

由于您的代码中没有return dfs(nei,c^1) ,因此似乎返回None。我将确保您明确返回所需的位置。例如,您可能要添加两个return语句:

dfs()
您的return dfs(node) 函数中的

以及:

possibleBipartition()

在您的public class TodayFragment extends Fragment { //initialisations Runnable mTicker; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final Handler mHandler = new Handler(); mTicker = new Runnable() { @Override public void run() { // user interface interactions and updates on screen mHandler.postDelayed(mTicker, 1000); } }; mHandler.postDelayed(mTicker, 1000); return inflater.inflate(R.layout.fragment_today, container, false);; } 函数中。

请注意,如果有Racket和Haskell之类的语言中不存在返回值,则需要在Python中明确指定返回值。

答案 1 :(得分:0)

表面上,该函数返回None,因为您没有return语句。因此,功能bibisBipartition不会返回任何内容(即,无)。这只是python允许您无任何错误地执行的语法操作,这可能会使新手感到困惑。您将需要从函数中返回一些内容,以使打印语句不仅仅打印None。一个好主意可能是当且仅当可能的Bipartition有效时才返回True。

您可以进行的一种调整是检查在函数中建立的颜色字典,以查看“ possibleBipartition”是否有效。这可以通过以下事实来实现:如果每个顶点仅属于一种颜色(在您的情况下为0或1),则图具有有效的双重分配。