2013-01-19 46 views
1

我已經從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() 

我want't地圖是這樣一個圖:

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

其中A,B,C,d是國家的名字。

+0

不'printMap()'給出所需輸出??? – namit

+0

是的但我希望它打印國家的名稱,而不是ID。 – Sajjad

+0

以及'A','B','C'和'D'如何與輸入Map關聯?我的意思是他們如何與'[[1,4,2,5],[0,4,6,5] ...有關。 .' ??? – namit

回答

2

主要思想是定義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]會爲您提供該國家的字符串名稱。


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 cindex[country] >= len(Map): 
     return True 
    if okToColor(Map, country, color): 
     mapColors[country] = color 
     for color in colors: 
      try: 
       next_country = countries[cindex[country] + 1] 
      except IndexError: 
       return True 
      if explore(Map, next_country, color): 
       return True 
    return False 


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

countries = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] 
cindex = dict(zip(countries, range(len(countries)))) 
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]] 
Map = {countries[idx]: [countries[n] for n in item] for idx, 
     item in enumerate(Map)} 
result = explore(Map, 'A', 'Red') 
print(result) 
printMap() 

產生

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

我希望Map是:Map = {'A':['B','C'],'B':['A','D'],...}。我不想在地圖中使用ID。 – Sajjad

+1

您可以將Map映射爲Map = {'A':['B','C'],'B':['A','D'],...}'。我用來定義'Map'的代碼只是將你的前一個例子轉換成正確的格式。 – unutbu

+0

但是當我把地圖寫成Map = {'A':['B','C'],'B':['A','D']}'我得到這個錯誤:'Map = {國家[idx]:[國家[n]爲項目]爲idx,項目在枚舉(地圖)} TypeError:列表索引必須是整數,而不是str' – Sajjad

相關問題