Advertisement
kosievdmerwe

399

Apr 29th, 2022
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 0 0
  1. class Solution:
  2.     def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
  3.         adjacency = defaultdict(set)
  4.         costs = {}
  5.        
  6.         def add(a, b, v):
  7.             if a == b:
  8.                 return
  9.                
  10.             costs[(a, b)] = v
  11.             costs[(b, a)] = 1.0 / v
  12.             adjacency[a].add(b)
  13.             adjacency[b].add(a)
  14.        
  15.        
  16.         for (a, b), v in zip(equations, values):
  17.             add(a, b, v)
  18.            
  19.        
  20.         def calc(a: str, b: str) -> float:
  21.             if a == b and a in adjacency.keys():
  22.                 return 1.0
  23.            
  24.             if (a, b) in costs.keys():
  25.                 return costs[(a, b)]
  26.            
  27.             q = deque(
  28.                 (x, costs[(a, x)])
  29.                 for x in adjacency[a]
  30.             )  # Contains all a / x values we've discovered
  31.            
  32.             seen = set()
  33.             while q:
  34.                 cur_x, cur_val = q.popleft()
  35.                 if cur_x in seen:
  36.                     continue
  37.                 seen.add(cur_x)
  38.                
  39.                 for next_x in adjacency[cur_x]:
  40.                     if next_x in seen:
  41.                         continue
  42.                        
  43.                     next_val = cur_val * costs[(cur_x, next_x)]
  44.                     if next_x == b:
  45.                         return next_val
  46.                     q.append((next_x, next_val))        
  47.                
  48.             return -1.0
  49.            
  50.        
  51.         return [calc(a, b) for a, b in queries]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement