1 class Solution: 2 def calcEquation(self, equations: 'List[List[str]]', values: 'List[float]', queries: 'List[List[str]]') -> 'List[float]': 3 sets = set() 4 for eq in equations: 5 sets.add(eq[0]) 6 sets.add(eq[1]) 7 l = sorted(list(sets)) 8 n = len(l) 9 l1 = [[x] for x in l] 10 l2 = [[1.0]] * n 11 12 nx = len(equations) 13 for i in range(nx): 14 p1 = equations[i][0] 15 p2 = equations[i][1] 16 pp = values[i] 17 if pp <= 1.0: 18 p1,p2 = p2,p1 19 pp = 1/pp 20 print(p1,p2,pp) 21 22 i1 = 0 23 i2 = 0 24 i22 = 0 25 ct = 0 26 for j in range(len(l1)): 27 if p1 in l1[j]: 28 i1 = j 29 i11 = l1[j].index(p1) 30 ct += 1 31 if p2 in l1[j]: 32 i2 = j 33 i22 = l1[j].index(p2) 34 ct += 1 35 if ct==2: 36 break 37 l2[i1] = [y * pp * l2[i2][i22] / l2[i1][i11] for y in l2[i1]] 38 l2[i1] = l2[i1] + l2[i2] 39 l2.pop(i2) 40 l1[i1] = l1[i1] + l1[i2] 41 l1.pop(i2) 42 43 result = list() 44 for i in range(len(queries)): 45 q1 = queries[i][0] 46 q2 = queries[i][1] 47 if q1 not in l or q2 not in l: 48 result.append(-1.0) 49 else: 50 qi1 = 0 51 qi2 = 0 52 ct2 = 0 53 for j in range(len(l1)): 54 if q1 in l1[j]: 55 qi1 = j 56 ct2 += 1 57 if q2 in l1[j]: 58 qi2 = j 59 ct2 += 1 60 if ct2 == 2: 61 break 62 if qi1 != qi2: 63 result.append(-1.0) 64 else: 65 k1 = l1[qi1].index(q1) 66 k2 = l1[qi1].index(q2) 67 v1 = l2[qi2][k1] 68 v2 = l2[qi2][k2] 69 result.append(v1/v2) 70 71 return result
纯集合运算,能写出来感觉还是很牛逼的,哈哈。