2014-06-29 28 views
1

給出了一個映射,由一個以逗號分隔的雙位數字的字符串表示,例如「12,23,34,45,56,67,78,81」,其中每對數字代表兩個數字之間的路徑,convert將字符串轉換爲以字典表示的圖形,其中鍵爲來源(數字),值爲來自鍵的可用目的地。 e.g 1:[2,8] 2 [3]等 這是我很醜陋的嘗試:將由鍵值對的字符串表示的圖轉換爲字典。 Python

def path(way): 
x = way.split(',') 
y = sorted(set(tele.replace(',',''))) 
graph = dict() 
for i in x: 
    for j in range(len(i)): 
     for h in y: 
      if h in i and i[j] != h: 
       if h in graph: 
        graph[h].append((i[j])) 
       else: 
        graph[h] = [(i[j])] 
return graph 

我打算在執行此之後,廣度優先搜索算法,以便找到最佳路徑。如果我的解釋不清楚,我很抱歉。任何幫助將非常感激,謝謝!

+0

是什麼'1:[2,8]'是什麼意思?它是一個無向圖嗎? – Pavel

+0

是的,對不清楚的解釋感到抱歉。這意味着從第1點開始,您可以移動到第8點或第2點。 – user3636636

回答

1
# this initializes values in the dictionary d with empty lists 
# so that we can directly call .append() without checking "if key in keys" 
from collections import defaultdict 
d = defaultdict(list) 

# your input string 
s = "12,23,34,45,56,67,78,81" 

# iterate through digit pairs 
for pair in s.split(","): 
    # get single digits from a pair 
    fr = pair[0] 
    to = pair[1] 

    # add edges in both directions (undirected) 
    d[fr].append(to) 
    d[to].append(fr) 

# see what we got 
print d 

結果

{'1': ['2', '8'], '3': ['2', '4'], '2': ['1', '3'], '5': ['4', '6'], '4': ['3', '5'], '7': ['6', '8'], '6': ['5', '7'], '8': ['7', '1']} 
+2

可能要考慮設置值以避免重複路徑。 – wwii

+0

這會非常有幫助。任何建議如何解決這個問題?對不起,我對編程比較陌生。謝謝@wwii – user3636636

+0

使用set而不是defaultdict列表。使用(set)add方法而不是(list)append方法來添加邊/節點/路徑。看看Python文檔以查看這些類型和方法的進一步解釋。 – wwii

相關問題