399. Evaluate Division
equations = [ ["a", "b"], ["b", "c"] ],
values = [2.0, 3.0],
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].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]
"""
q = collections.defaultdict(dict)
# build the graph by building the adj list
for (a, b) , val in zip(equations, values):
# identity
q[a][a] = q[b][b] = 1.0
q[a][b] = val
q[b][a] = 1/val
for k in q:
for i in q[k]:
for j in q[k]:
q[i][j] = q[i][k] * q[k][j] # connecting nodes explicitly
return [q[a].get(b, -1.0) for a , b in queries]Last updated
Was this helpful?