【问题标题】:Coloring a random graph in python在python中为随机图着色
【发布时间】:2022-01-19 15:55:30
【问题描述】:

我有一个在 python 中实现贪婪着色的脚本,换句话说,它用四种颜色为图形着色。我想生成一个随机图,然后将其传递到上面链接上的脚本中以对其进行着色。 这就是我生成随机图的方式(以字典的形式):

list = [1,2,3,4,5]
d = {i: sample([j for j in q if i != j], randrange(1, len(q) - 1))
for i in q}

所以我现在需要的是将创建的字典传递给贪婪着色脚本的某种函数,因为如果我在名为 greedycoloring 的脚本中的函数中输入图形 d,我会得到以下信息错误:

    Traceback (most recent call last):
  File "/private/var/mobile/Containers/Shared/AppGroup/9244016A-6D10-4627-B39B-6D63D3F9D22C/Pythonista3/Documents/nuovaprova.py", line 88, in <module>
    greedyColoring(d, 5)
  File "/private/var/mobile/Containers/Shared/AppGroup/9244016A-6D10-4627-B39B-6D63D3F9D22C/Pythonista3/Documents/nuovaprova.py", line 33, in greedyColoring
    if (result[i] != -1):
IndexError: list index out of range

【问题讨论】:

  • 你应该可以使用greedycoloring(d,5)
  • 我收到错误“列表索引超出范围”
  • 您能否edit 并将完整的错误消息粘贴到您的问题中?
  • 我添加了执行“greedycoloring(d,5)”时遇到的错误

标签: python arrays list dictionary random


【解决方案1】:

从0开始listq如下图:

q = [0, 1, 2, 3, 4]
d = {i: sample([j for j in q if i != j], randrange(1, len(q) - 1))
     for i in q}

然后,您可以直接将字典d 传递到脚本中:

 greedyColoring(d, 5)

给定的脚本将graph表示为list of lists,其中list的索引表示节点,其对应的值表示其相邻节点,因此您也可以将d转换为[node for node in d.values()]的列表列表,然后传递给函数如:

greedyColoring([node for node in d.values()], 5) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-08
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多