-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluateDivision.py
More file actions
29 lines (22 loc) · 1013 Bytes
/
Copy pathevaluateDivision.py
File metadata and controls
29 lines (22 loc) · 1013 Bytes
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
from collections import defaultdict, deque
class Solution:
def calcEquation(self, equations: list[list[str]], values: list[float], queries: list[list[str]]) -> list[float]:
graph = defaultdict(list)
for (a, b), value in zip(equations, values):
graph[a].append((b, value))
graph[b].append((a, 1/value))
def bfs(start: str, end: str) -> float:
if start not in graph or end not in graph: return -1
if start == end: return 1
queue = deque([(start, 1)])
visited = set()
while queue:
node, weight = queue.popleft()
visited.add(node)
for dest, dest_weight in graph[node]:
if dest in visited: continue
if end == dest:
return weight * dest_weight
queue.append((dest, weight * dest_weight))
return -1
return [bfs(start, end) for start, end in queries]