【发布时间】:2016-05-26 11:21:25
【问题描述】:
我编写了以下程序,但有 2 个“错误”我不知道如何解决。输入 b1、c1、d1 和 e1 对应于点和相邻节点。 例如,如果我给出输入:A B C,这意味着您可以从 A 点前往 B 和 C。输入 f1 对应于起点和终点。例如,如果我输入:A D,这意味着您从 A 点开始并希望在 D 点结束。
b1 = input()
c1 = input()
d1 = input()
e1 = input()
f1 = input()
b = b1.split()
c = c1.split()
d = d1.split()
e = e1.split()
f = f1.split()
b_node = b[1:]
c_node = c[1:]
d_code = d[1:]
e_node = e[1:]
f_node = f[1:]
G = {b[0]:b_node, c[0]:c_node, d[0]:d_node, e[0]:e_node}
def find_path(graph, start, end, path = []):
path = path + [start]
newpath = []
if start == end:
return path
shortest = None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath:
if not shortest or len(newpath)<len(shortest):
shortest = newpath
return shortest
print(find_path(G, f[0], f[1]))
我给我的程序以下输入
A B C
B A C
C B D
D
A D
我的问题如下: 1. 我的程序出错,因为 d_node = [] (empty)。然而,这是 应该是这样,因为从 D 点开始,您不能前往任何点!我怎样才能让它正确运行? 2.有没有办法让我的程序要求一个数字'N'点,然后给我N行来为这些点提供所有相邻的信息?我尝试了一些形式
input_list = []
x = int(input())
for i in range(x):
input_list.append(input())
但不能让它工作..有什么想法吗?
【问题讨论】:
标签: python-3.x input shortest-path is-empty