avatarJ3

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4978

Abstract

ths</span>(<span class="hljs-params">graph, start, <span class="hljs-keyword">end</span>, path=[]</span>)<span class="hljs-symbol">:</span></pre></div><div id="fb7d"><pre> <span class="hljs-built_in">path</span> = <span class="hljs-built_in">path</span> + [<span class="hljs-built_in">start</span>]</pre></div><div id="5020"><pre> <span class="hljs-keyword">if</span> <span class="hljs-built_in">start</span> == <span class="hljs-keyword">end</span>:</pre></div><div id="7800"><pre> <span class="hljs-keyword">return</span> [path]</pre></div><div id="23bd"><pre> <span class="hljs-keyword">if</span><span class="hljs-built_in"> not</span> <span class="hljs-keyword">start</span> <span class="hljs-keyword">in</span> graph:</pre></div><div id="9be6"><pre> <span class="hljs-keyword">return</span> []</pre></div><div id="279d"><pre> <span class="hljs-attr">paths</span> = []</pre></div><div id="27bb"><pre> for <span class="hljs-keyword">node</span> <span class="hljs-title">in</span> graph[<span class="hljs-literal">start</span>]:</pre></div><div id="781d"><pre> if <span class="hljs-keyword">node</span> <span class="hljs-title">not</span> <span class="hljs-keyword">in</span> path:</pre></div><div id="43d4"><pre> newpaths = find_all_paths(graph, <span class="hljs-keyword">node</span><span class="hljs-title">, end</span>, path)</pre></div><div id="4c23"><pre> <span class="hljs-keyword">for</span> <span class="hljs-keyword">new</span><span class="hljs-type">path</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">new</span><span class="hljs-type">paths</span>:</pre></div><div id="ac6d"><pre> paths.append(<span class="hljs-keyword">new</span><span class="hljs-type">path</span>)</pre></div><div id="752e"><pre> <span class="hljs-keyword">return</span> paths</pre></div><p id="bca4">Running:</p><div id="5c43"><pre><span class="hljs-function"><span class="hljs-title">find_all_paths</span><span class="hljs-params">(graph, <span class="hljs-string">'A'</span>, <span class="hljs-string">'D'</span>)</span></span></pre></div><div id="7bf8"><pre>[[<span class="hljs-symbol">'A</span>', <span class="hljs-symbol">'B</span>', <span class="hljs-symbol">'C</span>', <span class="hljs-symbol">'D</span>'], [<span class="hljs-symbol">'A</span>', <span class="hljs-symbol">'B</span>', <span class="hljs-symbol">'D</span>'], [<span class="hljs-symbol">'A</span>', <span class="hljs-symbol">'C</span>', <span class="hljs-symbol">'D</span>']]</pre></div><figure id="0d62"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*yJjZ9G179kxm0ddjJoNdyQ.png"><figcaption></figcaption></figure><h1 id="3ae4">Find The Path of 0 to 4:</h1><div id="5d79"><pre><span class="hljs-attribute">graph</span> <span class="hljs-operator">=</span> {</pre></div><div id="095b"><pre><span class="hljs-string">'0'</span>: [<span class="hljs-string">'1'</span>, <span class="hljs-string">'2'</span>],</pre></div><div id="72fc"><pre><span class="hljs-string">'1'</span>: [<span class="hljs-string">'0'</span>, <span class="hljs-string">'3'</span>],</pre></div><div id="ee12"><pre><span class="hljs-string">'2'</span>: [<span class="hljs-string">'0'</span>, <span class="hljs-string">'3'</span>],</pre></div><div id="e420"><pre><span class="hljs-string">'3'</span>: [<span class="hljs-string">'1'</span>, <span class="hljs-string">'2'</span>, <span class="hljs-string">'4'</span>, <span class="hljs-string">'5'</span>],</pre></div><div id="7db4"><pre><span class="hljs-string">'4'</span>: [<span class="hljs-string">'3'</span>],</pre></div><div id="e767"><pre><span class="hljs-symbol">'5</span><span class="hljs-symbol">':</span> [<span class="hljs-symbol">'3</span>']</pre></div><div id="81c1"><pre>}</pre></div><p id="9412">Running:</p><div id="6e5e"><pre><span class="hljs-function"><span class="hljs-title">find_all_paths</span><span class="hljs-params">(graph, <span class="hljs-string">'0'</span>, <span class="hljs-string">'4'</span>)</span></span></pre></div><div id="be34"><pre>[[<span class="hljs-symbol">'0</span>', <span class="hljs-symbol">'1</span>', <span class="hljs-symbol">'3</span>', <span class="hljs-symbol">'4</span>'], [<span class="hljs-symbol">'0</span>', <span class="hljs-symbol">'2</span>', <span class="hljs-symbol">'3</span>', <span class="hljs-symbol">'4</span>']]</pre></div><h1 id="10fc">Find the Shortest Path of 0 to 5:</h1><div id="df00"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">find_shortest_path</span>(<span class="hljs-params">graph, start, <span class="hljs-keyword">end</span>, path=[]</span>)<span class="hljs-symbol">:</span></pre></div><div id="e60c"><pre> <span class="hljs-built_in">path</span> = <span class="hljs-built_in">path</span> + [<span class="hljs-built_in">start</span>]</pre></div><div id="84e6"><pre> <span class="hljs-keyword">if</span> <span class="hljs-built_in">start</span> == <span class="hljs-keyw

Options

ord">end</span>:</pre></div><div id="9c8e"><pre> <span class="hljs-keyword">return</span> path</pre></div><div id="aeec"><pre> <span class="hljs-keyword">if</span><span class="hljs-built_in"> not</span> <span class="hljs-keyword">start</span> <span class="hljs-keyword">in</span> graph:</pre></div><div id="8e16"><pre> <span class="hljs-keyword">return</span> <span class="hljs-built_in">None</span></pre></div><div id="3989"><pre> <span class="hljs-attr">shortest</span> = None</pre></div><div id="59d4"><pre>for <span class="hljs-keyword">node</span> <span class="hljs-title">in</span> graph[<span class="hljs-literal">start</span>]:</pre></div><div id="bf9b"><pre> if <span class="hljs-keyword">node</span> <span class="hljs-title">not</span> <span class="hljs-keyword">in</span> path:</pre></div><div id="b57e"><pre> newpath = find_shortest_path(graph, <span class="hljs-keyword">node</span><span class="hljs-title">, end</span>, path)</pre></div><div id="6d0d"><pre> <span class="hljs-keyword">if</span> <span class="hljs-keyword">new</span><span class="hljs-type">path</span>:</pre></div><div id="de5c"><pre> if not shortest or <span class="hljs-built_in">len</span>(newpath) < <span class="hljs-built_in">len</span>(shortest):</pre></div><div id="4a74"><pre> <span class="hljs-attr">shortest</span> = newpath</pre></div><div id="e239"><pre><span class="hljs-keyword">return</span> shortest</pre></div><p id="b2d5">Running:</p><div id="28ce"><pre><span class="hljs-function"><span class="hljs-title">find_shortest_path</span><span class="hljs-params">(graph, <span class="hljs-string">'0'</span>, <span class="hljs-string">'5'</span>)</span></span></pre></div><div id="0c5e"><pre>[<span class="hljs-symbol">'0</span>', <span class="hljs-symbol">'1</span>', <span class="hljs-symbol">'3</span>', <span class="hljs-symbol">'5</span>']</pre></div><p id="3004">That’s All, Folks o/</p><div id="12b6"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-string">"That's it! Have a nice day! Favorite it, if you like!"</span>)</span></span></pre></div><div id="3b48"><pre>That's <span class="hljs-keyword">it</span>! Have a nice <span class="hljs-built_in">day</span>! Favorite <span class="hljs-keyword">it</span>, <span class="hljs-keyword">if</span> you like!</pre></div><p id="1e32">Until next time!</p><p id="d50d">👉Jupiter notebook <a href="https://drive.google.com/drive/folders/1-QiJSBEHsTpR9bfJh3vCTlbhz5_f4jNl?usp=sharing">link</a> :)</p><p id="61cd">👉or collab <a href="https://drive.google.com/file/d/1O_gwBAIWzgY1zaHjd1hFpJNQd9_Ozso_/view?usp=sharing">link</a></p><p id="bc25">👉<a href="https://github.com/giljr/my_jupyter_notebook">git</a></p><h2 id="a35d">Credits And References</h2><p id="09c3"><a href="https://www.linkedin.com/in/borinvini/"><b>Vinicius Pozzobon Borin</b></a><b></b>PhD Student at UTFPR (CPGEI/LABSC — Wireless Communications) and Professor at UNINTER (face-to-face and distance ed.)</p><h1 id="e9d6">Related Posts</h1><p id="65a3"><b>00</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/lambda-in-python-421b0c18e825"><b>Lambda in Python </b></a>— Python Lambda Desmistification</p><p id="4057"><b>01</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/send-emails-using-python-jupyter-notebook-94d14a5a5655"><b>Send Email in Python</b></a> — Using Jupyter Notebook — How To Send Gmail In Python</p><p id="5c94"><b>02</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/automate-your-email-marketing-with-python-f0d68234b789"><b>Automate Your Email With Python & Outlook</b></a><b> </b>— How To Create An Email Trigger System in Python</p><p id="78de"><b>03</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/manipulating-files-with-python-3f9a781287e9"><b>Manipulating Files With Python</b></a> — Manage Your Lovely Photos With Python!</p><p id="9259"><b>04</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/pandas-dataframe-advanced-48f83a5b097f"><b>Pandas DataFrame Advanced </b></a>— A Complete Notebook Review</p><p id="e3a7"><b>05</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/is-this-leap-year-python-calendar-3d1a61f2c4a7"><b>Is This Leap Year? Python Calendar</b> </a>— How To Calculate If The Year Is Leap Year and How Many Days Are In The Month</p><p id="6145"><b>06</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/list-comprehension-in-python-c22c4b0a6a8a"><b>List Comprehension In Python </b></a>— Locked-in Secrets About List Comprehension</p><p id="bf9f"><b>07</b>#Episode#PurePythonSeries —Graphs — In Python — Extremely Simple Algorithms in Python (this one)</p><p id="d2c9"><b>08</b>#Episode#PurePythonSeries — <a href="https://readmedium.com/decorator-in-python-62c00f7e818"><b>Decorator in Python </b></a>— How To Simplifying Your Code And Boost Your Function</p></article></body>

Graphs — In Python

Extremely Simple Algorithms in Python #PurePythonSeries — Episode #07

Graphs are networks consisting of nodes connected by edges or arcs.

In directed graphs, the connections between nodes have a direction, and are called arcs;

in undirected graphs, the connections have no direction and are called edges.

We mainly discuss directed graphs.

Algorithms in graphs include finding a path between two nodes, finding the shortest path between two nodes, determining cycles in the graph (a cycle is a non-empty path from a node to itself), finding a path that reaches all nodes (the famous “traveling salesman problem”), and so on.

Sometimes the nodes or arcs of a graph have weights or costs associated with them, and we are interested in finding the cheapest path.

Let’s Practice Graphs with Python :)

Find The Path of A to D:

graph = {
'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']
}

A simple function to find the path:

def find_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if not start in graph:
        return None
    for node in graph[start]:
    if node not in path:
        newpath = find_path(graph, node, end, path)
     if newpath: return newpath
         return None

Running it now:

find_path(graph, 'A', 'D')
['A', 'B', 'C', 'D']

Now, Find the Path E to D:

find_path(graph, 'E', 'D')
['E', 'F', 'C', 'D']

Finding ALL PATHS:

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]
    if not start in graph:
        return []
        paths = []
    for node in graph[start]:
        if node not in path:
        newpaths = find_all_paths(graph, node, end, path)
    for newpath in newpaths:
        paths.append(newpath)
        return paths

Running:

find_all_paths(graph, 'A', 'D')
[['A', 'B', 'C', 'D'], ['A', 'B', 'D'], ['A', 'C', 'D']]

Find The Path of 0 to 4:

graph = {
'0': ['1', '2'],
'1': ['0', '3'],
'2': ['0', '3'],
'3': ['1', '2', '4', '5'],
'4': ['3'],
'5': ['3']
}

Running:

find_all_paths(graph, '0', '4')
[['0', '1', '3', '4'], ['0', '2', '3', '4']]

Find the Shortest Path of 0 to 5:

def find_shortest_path(graph, start, end, path=[]):
    path = path + [start]
        if start == end:
            return path
        if not start in graph:
            return None
    shortest = None
for node in graph[start]:
    if node not in path:
        newpath = find_shortest_path(graph, node, end, path)
        if newpath:
            if not shortest or len(newpath) < len(shortest):
                shortest = newpath
return shortest

Running:

find_shortest_path(graph, '0', '5')
['0', '1', '3', '5']

That’s All, Folks o/

print("That's it! Have a nice day! Favorite it, if you like!")
That's it! Have a nice day! Favorite it, if you like!

Until next time!

👉Jupiter notebook link :)

👉or collab link

👉git

Credits And References

Vinicius Pozzobon BorinPhD Student at UTFPR (CPGEI/LABSC — Wireless Communications) and Professor at UNINTER (face-to-face and distance ed.)

Related Posts

00#Episode#PurePythonSeries — Lambda in Python — Python Lambda Desmistification

01#Episode#PurePythonSeries — Send Email in Python — Using Jupyter Notebook — How To Send Gmail In Python

02#Episode#PurePythonSeries — Automate Your Email With Python & Outlook — How To Create An Email Trigger System in Python

03#Episode#PurePythonSeries — Manipulating Files With Python — Manage Your Lovely Photos With Python!

04#Episode#PurePythonSeries — Pandas DataFrame Advanced — A Complete Notebook Review

05#Episode#PurePythonSeries — Is This Leap Year? Python Calendar — How To Calculate If The Year Is Leap Year and How Many Days Are In The Month

06#Episode#PurePythonSeries — List Comprehension In Python — Locked-in Secrets About List Comprehension

07#Episode#PurePythonSeries —Graphs — In Python — Extremely Simple Algorithms in Python (this one)

08#Episode#PurePythonSeries — Decorator in Python — How To Simplifying Your Code And Boost Your Function

Graph
Python3
Find Shortest Path
Algorithms
Algorithm In Python
Recommended from ReadMedium