将搜索方法转换为搜索字符串列表

时间:2016-02-23 05:25:13

标签: python search depth-first-search

对于这个DFS函数,我正在尝试转换它,所以我可以使用字符串列表而不是整数,但我不知道如何去做。我尝试将if(未访问[v]):行更改为'如果v未访问'以使用字符串但我遇到了多个错误。现在该函数仍然采用int列表,但我评论了我试图做出的改变。为了搜索这个功能,我还需要改变什么呢?

def dfs(l1, x):
stack = []
stack.append(x)
n = len(l1)
visited = []
for i in range(0,n):
    visited.append(False)

while(len(stack)>0):
    v = stack.pop()
    if(not visited[v]):  #if v not in visited
        visited[v] = True #Problem with boolean 
        print(v, " ", end='')

        stack_aux = []
        for w in l1[v]:         #for w in l1
            if(not visited[w]): #if w not in visited
                stack_aux.append(w) 
        while(len(stack_aux)>0):
            stack.append(stack_aux.pop())

----------------------------------------------- -------------------

l1 = [['1','2','3'],['4'],['5','6'],['7','8'],[''] ,['9','10','11'],['12','13','14'],[''],[''],[''],[''],[ ''],[''],[''],['']]

1 个答案:

答案 0 :(得分:1)

假设您正在操作字典而不是列表,并且值是该字典中的键,那么更改代码以处理字符串非常简单。注意:更改为yield而不是打印,这只会产生节点列表:

def dfs_iterative(adjLists, s):
    stack = [s]
    visited = set()

    while stack:
        v = stack.pop()
        if v in visited:
            continue

        visited.add(v)
        yield v
        for w in adjLists.get(v, []):
            stack.append(w)

>>> adjLists1 = {'0':['1','2','3'], '1':['4'], '2':['5','6'], '3':['7','8'], '4':[], 
...              '5':['9','10','11'], '6':['12','13','14'], '7':[], '8':[]}
>>> list(dfs_iterative(adjLists1, '2'))
['2', '6', '14', '13', '12', '5', '11', '10', '9']
>>> ' '.join(dfs_iterative(adjLists1, '2'))
'2 6 14 13 12 5 11 10 9'

注意:改为收益