Python 编写此程序的更好方法

Python 编写此程序的更好方法,python,Python,我已经从java程序转换了以下代码块。如何在Map中使用国家名称而不是ID来书写国家名称 from collections import defaultdict colors = ['Red', 'Yellow', 'Green', 'Blue'] mapColors = defaultdict(str) def okToColor(Map ,country, color): for c in Map[country]: if mapColors[c] == color

我已经从java程序转换了以下代码块。如何在
Map
中使用国家名称而不是ID来书写国家名称

from collections import defaultdict
colors = ['Red', 'Yellow', 'Green', 'Blue']
mapColors = defaultdict(str)

def okToColor(Map ,country, color):
    for c in Map[country]:
        if mapColors[c] == color: return False
    return True

def explore(Map, country, color):
    if country >= len(Map): return True
    if okToColor(Map, country, color):
        mapColors[country] = color
        for color in colors:
            if explore(Map, country + 1, color): return True
    return False

def printMap():
    for c in mapColors:
        print c, mapColors[c]

Map = [[1, 4, 2, 5], [0, 4, 6, 5], [0, 4, 3, 6, 5], [2, 4, 6],
        [0, 1, 6, 3, 2], [2, 6, 1, 0], [2, 3, 4, 1, 5]]
result = explore(Map, 0, 'Red')
print result
printMap()
我不希望地图是这样的图形:

Map = { 'A':['B', 'C'], 'B':['A','D'], ...}

其中A、B、C、D是国家的名称。

主要思想是定义
国家和数字指数之间的映射:

countries = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
cindex = dict(zip(countries, range(len(countries))))
# {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6}
然后,只需稍作更改,就可以使用原始代码。以前的
country
是一个数字索引,现在需要数字索引时,你就把
cindex[country]
放进去

当您需要反转映射时,
countries[index]
会为您提供国家的字符串名称


屈服

True
A Red
C Yellow
B Yellow
E Green
D Red
G Blue
F Green

printMap()
是否提供了所需的输出???是的,但我希望它打印国家的名称而不是ID。以及
A
B
C
D
与输入地图的关系如何?我的意思是它们与
[[1,4,2,5],[0,4,6,5]…
??你是如何得到这些国家的?我还没有将这些字母映射到ID。它应该是这样的国家=['A','B','C',…]所以国家[0]是'A'。而ID 0映射到'A'。我希望映射为:{'A':['B','C','B':['A','D'],}。我不想在映射中创建ID。您可以将
映射编写为
映射={'A':['B','C'],'B':['A','D'],…}
。我用于定义
映射的代码只是将您以前的示例转换为正确的形式。但当我将映射编写为
映射时,{'A':['B','C'],'B':['A','D'}
Map={countries[idx]:[countries[n]for n in item]for idx,item in enumerate(Map)}TypeError:list index必须是整数,而不是str
注释掉那一行。这是我唯一用于将以前的数字映射转换为基于字符串的映射的行。
True
A Red
C Yellow
B Yellow
E Green
D Red
G Blue
F Green