简体   繁体   English

计算用于在python中为图形着色的颜色数量

[英]Count the number of colors used to color a graph in python

I need help with my code to count the number of colors that used to color the graph I wrote a small code to print a list of colors and now I need to count them 我需要帮助我的代码以计算用于对图形进行着色的颜色数量,我编写了一个小代码来打印颜色列表,现在我需要对它们进行计数

import networkx as nx
g = nx.Graph()
g.add_nodes_from([1,2,3,4,5])
g.add_edges_from([(1,2),(1,3),(1,4),(1,5),(4,5)])
C = set(xrange(12))
color = {}

for u in g:
    interdits = set([color[v] for v in g.neighbors(u) if color.has_key(v)])
    color[u] = min(C-interdits)

print color

the output : 输出 :

 {1: 0, 2: 1, 3: 1, 4: 1, 5: 2} 

instead of this output I want to count the colors so the result should be 3 Any idea or help?? 而不是这个输出,我想计算颜色,所以结果应该是3任何想法或帮助?? Thanks in advance 提前致谢

You should definitely read through a Python tutorial . 您绝对应该通读Python教程 You might also want to use ipython or IDLE or something where you can easily see what methods are living inside an object without having to consult the docs, which is an easy way to experiment. 您可能还想使用ipython或IDLE或其他可以轻松查看对象内部存在哪些方法而无需查阅文档的方法,这是一种简单的实验方法。 dir(some_object_name) works too but I don't find it as convenient as hitting tab in ipython, but YMMV. dir(some_object_name)也可以,但是我发现它不如在ipython中击中tab那样方便,但是YMMV却不如。

In any case, once you have your color variable: 无论如何,一旦有了color变量:

>>> color
{1: 0, 2: 1, 3: 1, 4: 1, 5: 2}
>>> color.values()
[0, 1, 1, 1, 2]
>>> set(color.values())
set([0, 1, 2])
>>> len(set(color.values()))
3

(And just to make sure, this the number of colours you used , not the minimum number of colours needed.) (并且要确保这是您使用的颜色数量,而不是所需的最小颜色数量。)

The highest number color used can be found with 可以找到使用最高编号的颜色

max(color.values())

but they're numbered from zero so you probably want 但它们从零开始编号,所以您可能想要

max(color.values()) + 1

While it likely doesn't really matter, this doesn't require building a list of all the colors used, or hashing each entry, unlike the set method. 尽管可能并不重要,但与set方法不同,这不需要构建所有使用颜色的列表或对每个条目进行哈希处理。

Also, has_key is deprecated. 同样,已弃用has_key Use v in color instead. 改为使用v in color

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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