Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
- g = defaultdict(list)
- for i, (a, b) in enumerate(equations):
- g[a].append((b, values[i]))
- g[b].append((a, 1/values[i]))
- def dfs(a, b):
- if a not in g or b not in g:
- return -1.0
- paths = dict()
- paths[a] = 1
- st = [a]
- while st:
- cur = st.pop()
- if cur == b:
- return paths[b]
- for n, w in g[cur]:
- if n not in paths:
- paths[n] = paths[cur] * w
- st.append(n)
- return -1.0
- res = []
- for a, b in queries:
- res.append(dfs(a, b))
- return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement