-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy path399_evaluate_division.py
More file actions
60 lines (46 loc) · 1.43 KB
/
399_evaluate_division.py
File metadata and controls
60 lines (46 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import collections
class Solution:
def calcEquation(self, equations, values, queries):
"""
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
ans = []
if not (
equations and
values and
queries and
len(equations) == len(values)
):
return ans
nexts = collections.defaultdict(set)
evals = collections.defaultdict(float)
for i in range(len(equations)):
a, b = equations[i]
nexts[a].add(b)
nexts[b].add(a)
evals[a, b] = 1.0 * values[i]
evals[b, a] = 1.0 / values[i]
for a, b in queries:
res = self.dfs(a, b, 1, nexts, evals, set())
ans.append(float(res))
return ans
def dfs(self, a, b, val, nexts, evals, visited):
res = -1
if a not in nexts:
return res
if a == b:
# this condition must be after `a not in nexts`
# to prevent the node not in graph
return val
visited.add(a)
for c in nexts[a]:
if c in visited or (a, c) not in evals:
continue
res = self.dfs(c, b, val * evals[a, c], nexts, evals, visited)
if res != -1:
break
visited.discard(a)
return res