[英]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).我正在尝试实现一个 function,它使用给定的父节点 object 打印源顶点和目标顶点之间的最短路径。function 应该返回一个使用“->”连接相邻顶点的 str(请参阅预期输出)。 How would i go about doing this?
我将如何 go 这样做?
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我预期的 output 是:s -> y -> x -> t -> z
This is what Ive done so far, but it doesnt get me the expected output.这是我到目前为止所做的,但它没有让我得到预期的 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']它给了我这个:['s', 'y', 'x', 't', 'z']
All you need to do is convert the list to the appropriate string using the .join()
method.您需要做的就是使用
.join()
方法将列表转换为适当的字符串。
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:此时我们得到了想要的 output:
s -> y -> x -> t -> z
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.