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上跑老是莫名的下移。比如这样(红色区...