class Solution(object):
def calcEquation(self, equations, values, queries):
"""
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
#Floyed-Warshall, find all shortest path in a graph
#dynamic programming
#default d[i][j]=inf, if d[i][k]+d[k][j]<d[i][j], replace d[i][j] with smaller value
#loop till all d[i][j] is smallest possible, or in the case of this problem, when all reachable point has been given value, none reachable points are left blank.
d=collections.defaultdict(dict)
for (numerator,denominator),value in zip(equations,values):
d[numerator][numerator]=d[denominator][denominator]=1.0
d[numerator][denominator]=value
d[denominator][numerator]=1.0/value
#find all possible permutations of all the notes in the graph
for k,i,j in itertools.permutations(d,3):
if k in d[i] and j in d[k]:
d[i][j]=d[i][k]*d[k][j]
return [d[numerator].get(denominator,-1) for (numerator,denominator) in queries]
399. Evaluate Division
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 入门级Hi-Res Audio高解析度耳机新低价。 天猫到手价265元(下单立减399-141)包邮,五一假期,有...
- 之前碰到过一个问题。 就是利用storyboard拖动出来的控件, 在iOS8上跑老是莫名的下移。比如这样(红色区...