﻿ Python Data Structures and Algorithms: Sort a list of elements using Topological sort - w3resource # Python Data Structures and Algorithms: Sort a list of elements using Topological sort

## Python Search and Sorting : Exercise-22 with Solution

Write a Python program to sort a list of elements using Topological sort.

Sample Solution:

Python Code:

``````# License https://bit.ly/2InTS3W
#     a
#    / \
#   b  c
#  / \
# d  e
edges = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []}
vertices = ['a', 'b', 'c', 'd', 'e']
def topological_sort(start, visited, sort):
"""Perform topolical sort on a directed acyclic graph."""
current = start
visited.append(current)
neighbors = edges[current]
for neighbor in neighbors:
# if neighbor not in visited, visit
if neighbor not in visited:
sort = topological_sort(neighbor, visited, sort)
# if all neighbors visited add current to sort
sort.append(current)
# if all vertices haven't been visited select a new one to visit
if len(visited) != len(vertices):
for vertice in vertices:
if vertice not in visited:
sort = topological_sort(vertice, visited, sort)
# return sort
return sort

sort = topological_sort('a', [], [])
print(sort)
```
```

Sample Output:

```['c', 'd', 'e', 'b', 'a']
```

Flowchart: What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz

﻿

## Python: Tips of the Day

Returns the maximum value of a list, after mapping each element to a value using the provided function

Example:

```def tips_max(lst, fn):
return max(map(fn, lst))

print(tips_max([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']))
```

Output:

```8
```