(data, train_graph, connected_components, training_data=True)
return result_distance
1. 如果q1,q2在一个连通图上：返回q1,q2的距离d
    2. 如果q1,q2不在一个连通图上: 令d(q1, q2) = 1000
1. 如果q1,q2在一个连通图上：返回q1,q2的距离d
    2. 如果q1,q2不在一个连通图上: 令d(q1, q2) = 1000
1 . 如果q1 q2在一个连通图上：返回q1 q2的距离d 2 . 如果q1 q2不在一个连通图上 : 令d ( q1 q2 ) = 1000
def get_graph_distance(data, train_graph, connected_components, training_data=True):
    '''
    1. 如果q1,q2在一个连通图上：返回q1,q2的距离d
    2. 如果q1,q2不在一个连通图上: 令d(q1, q2) = 1000
    '''
    n = data.shape[0]
    
    # 初始化
    record_distance = {}  #用来记录已经计算过的距离
    result_distance = [1000 for i in range(n)]
    
    for i in range(n):
        q1 = data.loc[i,'q1']
        q2 = data.loc[i,'q2']

        # 如果是训练数据的相似问题，则dist=1
        if training_data and data.loc[i,'label'] == 1:
            result_distance[i] = 1
        
        # 如果已经计算过，直接取出计算过的值
        elif (q1,q2) in record_distance.keys():
            result_distance[i] = record_distance[(q1,q2)]

        elif (q2,q1) in record_distance.keys():
            result_distance[i] = record_distance[(q2,q1)]

        else:       
            # check whether q1,q2 are in one connected_componets
            for cc in connected_components:
                if (q1 in cc) and (q2 in cc):
                    # 连通图cc,q1到其它节点的距离
                    q1_dist = Dijkstra(train_graph, cc, q1)
                    # 把计算过的距离保存起来
                    new_dict = dict([((q1,node),q1_dist[node]) for node in q1_dist.keys()])
                    record_distance.update(new_dict)          
                    result_distance[i] = q1_dist[q2]            
                    break

    result_distance = pd.DataFrame(np.array(result_distance), index=data.index)
    result_distance.columns = ['graph_distance']
    
    return result_distance
def get_graph_distance ( data , train_graph , connected_components , training_data = True ) : n = data . shape [ 0 ] # 初始化 record_distance = { } #用来记录已经计算过的距离 result_distance = [ 1000 for i in range ( n ) ] for i in range ( n ) : q1 = data . loc [ i , 'q1' ] q2 = data . loc [ i , 'q2' ] # 如果是训练数据的相似问题，则dist=1 if training_data and data . loc [ i , 'label' ] == 1 : result_distance [ i ] = 1 # 如果已经计算过，直接取出计算过的值 elif ( q1 , q2 ) in record_distance . keys ( ) : result_distance [ i ] = record_distance [ ( q1 , q2 ) ] elif ( q2 , q1 ) in record_distance . keys ( ) : result_distance [ i ] = record_distance [ ( q2 , q1 ) ] else : # check whether q1,q2 are in one connected_componets for cc in connected_components : if ( q1 in cc ) and ( q2 in cc ) : # 连通图cc,q1到其它节点的距离 q1_dist = Dijkstra ( train_graph , cc , q1 ) # 把计算过的距离保存起来 new_dict = dict ( [ ( ( q1 , node ) , q1_dist [ node ] ) for node in q1_dist . keys ( ) ] ) record_distance . update ( new_dict ) result_distance [ i ] = q1_dist [ q2 ] break result_distance = pd . DataFrame ( np . array ( result_distance ) , index = data . index ) result_distance . columns = [ 'graph_distance' ] return result_distance