[英]Finding shortest Path between two verticies with Parents object
我正在尝试实现一个 function,它使用给定的父节点 object 打印源顶点和目标顶点之间的最短路径。function 应该返回一个使用“->”连接相邻顶点的 str(请参阅预期输出)。 我将如何 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)
我预期的 output 是:s -> y -> x -> t -> z
这是我到目前为止所做的,但它没有让我得到预期的 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
它给了我这个:['s', 'y', 'x', 't', 'z']
您需要做的就是使用.join()
方法将列表转换为适当的字符串。
我们首先指定我们的分隔符:
" -> "
然后,我们可以使用分隔符连接列表中的字符串:
" -> ".join(['s', 'y', 'x', 't', 'z'])
此时我们得到了想要的 output:
s -> y -> x -> t -> z
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.