编写这个程序的更好方法

2024-10-04 05:25:25 发布

您现在位置: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: 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()

我不希望地图变成这样的图形:

^{pr2}$

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


Tags: intruemapforreturnifdef国家
1条回答
网友
1楼 · 发布于 2024-10-04 05:25:25

其主要思想是定义countries与数值索引之间的映射:

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]会给您国家的字符串名称。在


^{pr2}$

收益率

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

相关问题 更多 >