题目描述
贡献一个python答案
样例
class Solution(object):
def calcEquation(self, equations, values, queries):
"""
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
vertex = set()
path = collections.defaultdict(dict)
for (a, b), v in zip(equations, values):
path[a][b] = v
path[b][a] = 1/v
# 把记录过的点加入到vertex里去
vertex.add(a)
vertex.add(b)
# 把所有的点之间的距离都求出来,后面遍历就行了
for k in vertex:
for i in vertex:
for j in vertex:
# i/k * j/k = i/k, 得到i ~ k的距离
if k in path[i].keys() and j in path[k].keys():
path[i][j] = path[i][k] * path[k][j]
res = []
for q in queries:
up = q[0]
down = q[1]
# up/down 存在,返回结果
if down in path[up].keys():
res.append(path[up][down])
else:
res.append(-1)
return res