Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

dfs and bfs in python

def shortest_path(graph, start, goal):
    try:
        return next(bfs_paths(graph, start, goal))
    except StopIteration:
        return None

shortest_path(graph, 'A', 'F') # ['A', 'C', 'F']
Comment

dfs and bfs inn python

def dfs(graph, start):
    visited, stack = set(), [start]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.add(vertex)
            stack.extend(graph[vertex] - visited)
    return visited

dfs(graph, 'A') # {'E', 'D', 'F', 'A', 'C', 'B'}
Comment

dfs and bfs in python

def dfs_paths(graph, start, goal, path=None):
    if path is None:
        path = [start]
    if start == goal:
        yield path
    for next in graph[start] - set(path):
        yield from dfs_paths(graph, next, goal, path + [next])

list(dfs_paths(graph, 'C', 'F')) # [['C', 'F'], ['C', 'A', 'B', 'E', 'F']]
Comment

dfs and bfs in python

def bfs(graph, start):
    visited, queue = set(), [start]
    while queue:
        vertex = queue.pop(0)
        if vertex not in visited:
            visited.add(vertex)
            queue.extend(graph[vertex] - visited)
    return visited

bfs(graph, 'A') # {'B', 'C', 'A', 'F', 'D', 'E'}
Comment

PREVIOUS NEXT
Code Example
Python :: example of a bad code 
Python :: qq plot using seaborn with regression line 
Python :: passport ocr python 
Python :: how to print the fibonacci sequence in python using while loop 
Python :: fibonacci sequence script python 
Python :: python code to print fibonacci series 
Python :: auto instagram login 
Python :: pandas continues update csv 
Python :: conventional commits 
Python :: set_flip_h( false ) 
Python :: how to use methods defined within class 
Python :: operations in python 
Python :: disable network on pytest 
Python :: convert a column to camel case in python 
Python :: How can I use Apache Spark with notebook in Anaconda 
Python :: python how to close the turtle tab on click 
Python :: how to visualize pytorch model filters 
Python :: iterate rows 
Python :: how to convert nonetype to list in python 
Python :: pyqt grid layout 
Python :: math.floor python 
Python :: average values in a list python 
Python :: python online compiler with libraries 
Python :: how to sort list in python without sort function 
Python :: Using python permutations function on a list with extra function 
Python :: for i in range(6, 11): print(i, end="") 
Python :: passing list vs int in python important 
Python :: to iterate across information on same nest 
Python :: find a paragraph in requests-html 
Python :: no definition 
ADD CONTENT
Topic
Content
Source link
Name
9+4 =