Evaluate Division LeetCode solution in Python

1
class Solution:
2
def calcEquation(
3
self, equations: List[List[str]], values: List[float], queries: List[List[str]]
4
) -> List[float]:
5
graph = dict()
6

7
for (n, d), v in zip(equations, values):
8
if n not in graph:
9
graph[n] = []
10
if d not in graph:
11
graph[d] = []
12

13
graph[n].append((d, v))
14
graph[d].append((n, 1 / v))
15

16
def dfs(node, target, product, visited):
17
if n not in graph or d not in graph:
18
return -1
19

20
if node == target:
21
return product
22

23
visited.add(node)
24

25
for neighbor, quotient in graph[node]:
26
if neighbor not in visited:
27
soln = dfs(neighbor, target, product * quotient, visited)
28
if soln != -1:
29
return soln
30

31
return -1
32

33
solns = []
34
for n, d in queries:
35
solns.append(dfs(n, d, 1, set()))
36

37
return solns

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0