简体   繁体   中英

Finding shortest Path between two verticies with Parents object

I am trying to Implement a function that prints the shortest path between source and target vertices using a given parents object. The function should return a str that uses " -> " to connect adjacent vertices (see the expected output). How would i go about doing this?

def get_path(parents, source, target):
path = ''
### START YOUR CODE ###
pass
### END YOUR CODE ###

return path

# Do not change the test code here
path = get_path(parents, 's', 'z')
print(path)

My expected output is: s -> y -> x -> t -> z

This is what Ive done so far, but it doesnt get me the expected output.

def get_path(parents, source, target):
path = [target]
### START YOUR CODE ###
while True:
    key = parents[path[0]]
    path.insert(0, key)
    if key == source:
        break
### END YOUR CODE ###

return path

It gives me this: ['s', 'y', 'x', 't', 'z']

All you need to do is convert the list to the appropriate string using the .join() method.

We first specify our separator:

" -> "

Then, we can join the strings in our list using the separator:

" -> ".join(['s', 'y', 'x', 't', 'z'])

At which point we get the desired output:

s -> y -> x -> t -> z

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM