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 :: how to sort variable in specifiic order in python 
Python :: qq plot using seaborn 
Python :: iterating over the two ranges simultaneously and saving it in database 
Python :: generate fibonacci series in python 
Python :: fibonacci sequence python genorator 
Python :: sequencia de fibonacci python 
Python :: copy any files from one folder to another folder in python 
Python :: make my own rabbit bomb using python 
Python :: Horizontal bar graph OO interface 
Python :: activate inherit function django 
Python :: boto3 cross region 
Python :: removing rows dataframe not in another dataframe using two columns 
Python :: json timestamp to date python 
Python :: df.loc jupyter 
Python :: python get last cell value 
Python :: how to join models from another app 
Python :: check firebase email 
Python :: iterate 
Python :: vidgear python video streaming 
Python :: python concat list multiple times 
Python :: pandas from multiindex to single index 
Python :: pd.to_excel header char vertical 
Python :: how to limit variable godot 
Python :: looping emails using a database with python code 
Python :: Using Python Permutations function on a String with extra parameter 
Python :: python create named timer 
Python :: your momma in python 
Python :: uncompress zip file in pythonanywhere 
Python :: Find element with class name in requests-html python 
Python :: run all pycharm jupyter notebook 
ADD CONTENT
Topic
Content
Source link
Name
5+9 =