Finding a path using the Parents Array Recursively in Python

Rylai Crestfall

So I have a task, that is, to write a function that takes a parents array produced by a traversal, a starting vertex, and an end vertex, and produces a path from the start vertex to the end vertex.

I have tried writing the code for this

def tree_path(parents, start, end):
    if ((start == end) or (end == -1)):
        return [start, end]
    else:
        return tree_path(parents, start, parents[end])

It doesn't do what I intended for it to do. I'm not very good at recursion. Any help would be much appreciated. Thanks

JuniorCompressor

You can try, assuming we want a list of all vertices from start to end, the following:

def tree_path(parents, start, end):
    if (start == end) or (end == -1):
        return [start]
    else:
        return tree_path(parents, start, parents[end]) + [end]

If start coincides with end then our path consists only of one vertex: start. Otherwise, we find the path from start to the parent of end and to this path we add the end node.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Finding anagram using array list

From Dev

get all parents of xml node using python

From Dev

Finding path using algorithm A*

From Dev

Finding longest path in a dictionary in python

From Dev

Finding the average of an array using JS

From Dev

Finding md5 of files recursively in directory in python

From Dev

Finding an index in an array in python

From Dev

Recursion for finding the smallest path of numbers in an array

From Dev

Recursively finding indices of a string

From Dev

Recursively copying Content from one path to another of s3 buckets using boto in python

From Dev

Finding shortest path in 2d array

From Dev

Finding the max integer in an array, with specified start and ending indices in Java, **recursively**

From Dev

Finding the longest absolute file path using java

From Dev

Recursively finding with AWK

From Dev

Finding largest file recursively

From Dev

get all parents of xml node using python

From Dev

Finding a substring recursively

From Dev

Recursively finding the path to a node in a Binary Tree

From Dev

Finding a single path in a graph using dfs

From Dev

Finding empty directories recursively

From Dev

Regex for finding a string recursively?

From Dev

Path Finding (2D Array)

From Dev

Recursively finding indices of a string

From Dev

Recursively copying Content from one path to another of s3 buckets using boto in python

From Dev

Python: Finding the longest path

From Dev

Finding max in an array using recursion

From Dev

Finding parents by their children's properties

From Dev

Finding particular path in directory in Python

From Dev

Finding a Module's path, using the Module object

Related Related

HotTag

Archive