Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中返回所有可能的顶点着色组合_Python_Python 3.x - Fatal编程技术网

在Python中返回所有可能的顶点着色组合

在Python中返回所有可能的顶点着色组合,python,python-3.x,Python,Python 3.x,我被要求写一个方法三色(graph),将一个图作为输入,并返回该图所有可能的顶点颜色,包括无效的顶点颜色。我们使用字典表示图形,输出应该是字典列表 three_color({“A” : [“B”], “B” : [“A”]}) should return {“A” : 1, “B” : 1}, {“A” : 1, “B” : 2}, {“A” : 1, “B” : 3}, {“A” : 2, “B” : 1}, {“A” : 2, “B” : 2}, {“A” : 2, “B” : 3},

我被要求写一个方法三色(graph),将一个图作为输入,并返回该图所有可能的顶点颜色,包括无效的顶点颜色。我们使用字典表示图形,输出应该是字典列表

three_color({“A” : [“B”], “B” : [“A”]}) should return 

{“A” : 1, “B” : 1}, {“A” : 1, “B” : 2}, {“A” : 1, “B” : 3}, {“A” : 2, “B” : 1}, {“A” : 2, “B” : 2}, {“A” : 2, “B” : 3}, {“A” : 3, “B” : 1}, {“A” : 3, “B” : 2}, {“A” : 3, “B” : 3}
关于如何编写这个方法,我遇到了一些问题,因为我们不允许使用任何库(除了copy)来帮助我们

我是python新手,所以我不确定是否有一个我忽略的简单解决方案。非常感谢您的帮助或指导。 这就是我一直在努力解决的问题:

def three_color(graph):
    vertices = []
    colorings = []
    color = {}
    for key in graph:
        vertices.append(key)
    for v in vertices:
        color[v] = 1
    colorings.append(copy.copy(color))

    for v in vertices:
        for v2 in vertices:
            for i in range(1,4):
                for j in range(1,4):
                    color[v] = i
                    color[v2] = j
                    colorings.append(copy.copy(color))

    #Get rid of duplicates
    new_c = []
    for c in colorings:
        if c not in new_c:
            new_c.append(c)

    return new_c

我知道这是完全错误的,但我无法正确地思考这些for循环。

因为这是一个家庭作业问题,我将给出一个伪代码解决方案,您可以自己实现它,并希望通过这种方式了解更多

我偏爱递归,所以我将在这个解决方案中使用它

take a graph as an argument:
    if the graph is empty, return the graph
    recursively color all the elements except the first, store the result as "tail"
    store the first element of the list as "head"
    for every element of tail, refered to as "element":
        add "head, color 1" + element to a final results list
        add "head, color 2" + element to a final results list
        add "head, color 3" + element to a final results list
    return final results

请求家庭作业帮助是可以的,但我们希望海报能首先做出自己的努力。到目前为止你试过什么?你被卡在哪里了?请阅读和。我试过几个for循环。我的主要问题源于这样一个事实,即我的解决方案涉及的嵌套for循环数等于顶点数,这不仅会很多,而且还需要为每个可能的顶点数编写新代码。请包含您迄今为止尝试的代码,显示输出,或者如果出现错误,请包含完整的回溯,并显示此输入所需的输出。我所有的尝试都给了我缺少的顺序。正如我所说,我或多或少地在寻找指导,或者一个“提示”,帮助我开始解决问题。我已经花了好几个小时在这上面了,我只需要一个正确的方向。这就是你要解决的问题吗?即使您的代码不起作用,也要包含它,以便人们可以帮助您完成下一步。您创建了伪代码解决方案吗?这很有帮助。但这是不是会返回这样的词典列表?{A:1,B:1},{A:1,B:2},{A:1,B:3},{A:2,B:1},{A:2,B:2},{A:2,B:3},{A:3,B:1},{A:3,B:2},{A:3,B:3}它似乎正在返回一个单一颜色列表。这是伪代码,它可以返回您喜欢的任何类型。我写它的目的是返回一个字典列表,它可以做到这一点。