-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path399 Evaluate Division.py
84 lines (67 loc) · 2.46 KB
/
399 Evaluate Division.py
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""
Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number
(floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.
Example:
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
return [6.0, 0.5, -1.0, 1.0, -1.0 ].
The input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries ,
where equations.size() == values.size(), and the values are positive. This represents the equations. Return
vector<double>.
According to the example above:
equations = [ ["a", "b"], ["b", "c"] ],
values = [2.0, 3.0],
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].
Author: Rajeev Ranjan
"""
from collections import defaultdict
from itertools import izip
class Solution(object):
def calcEquation(self, equations, values, queries):
"""
transitive closure
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
G = defaultdict(dict)
for edge, val in izip(equations, values):
s, e = edge
G[s][e], G[e][s] = val, 1/val
G[s][s], G[e][e] = 1, 1
return [self.dfs(G, s, e, set()) for s, e in queries]
def dfs(self, G, s, e, path):
if s not in G or e not in G:
return -1.0
if e in G[s]:
return G[s][e]
for nbr in G[s]:
if nbr not in path:
path.add(nbr)
val = self.dfs(G, nbr, e, path)
if val != -1.0:
return val * G[s][nbr]
path.remove(nbr)
return -1.0
class Solution(object):
def calcEquation(self, equations, values, queries):
"""
Floyd-Warshall algorithm
transitive closure
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
G = defaultdict(dict)
for edge, val in izip(equations, values):
s, e = edge
G[s][e], G[e][s] = val, 1/val
G[s][s], G[e][e] = 1, 1
# Floyd-Warshall
for mid in G:
for s in G[mid]:
for e in G[mid]:
G[s][e] = G[s][mid] * G[mid][e]
return [G[s].get(e, -1.0) for s, e in queries]