如何在Python中创建一个正方形连接数组?

n1bvdmb6  于 2022-12-25  发布在  Python
关注(0)|答案(1)|浏览(151)

我在Berkeley Python关于数值方法的书中遇到了问题(从一本MATLAB书中拉出问题)然而,我发现答案中有几个错误,所以我把这个问题和它的示例输出一起发布。我在网上找到了一个MATLAB解决方案,但我不确定如何转换这个,因为我不确定示例输出是否告诉我正确的信息。所以,我想知道输出是否正确,然后如何推理将其转换为pyton解决方案。例如,如果列表长度为4,并且有4个列表,(4)怎么可能是一个可能的索引?
令C为包含0和1的正方形连通性数组。如果C [i,j]= 1,则我们说点i与点j有连接,或i连接到j。请注意,在此上下文中的连接是单向的,这意味着C [i,j]不一定与C [j,i]相同。例如,设想从点A到点B的单行道。如果A连接到B,则B不必连接到A。
写一个函数my_connectivity_mat_2_dict(C,names),其中C是一个连通性数组,names是表示一个点的名称的字符串列表,也就是说,names [i]是第i个点的名称。
输出变量节点应该是一个dict,其key是names中的字符串,value是一个包含索引j的向量,使得C [i,j]= 1。换句话说,它是点i连接到的点的列表。

    • 示例输出:**
C = [[0, 1, 0, 1], [1, 0, 0, 1], [0, 0, 0, 1], [1, 1, 1, 0]]
names = ['Los Angeles', 'New York', 'Miami', 'Dallas']
# Output: node['Los Angeles'] = [2, 4]
#         node['New York'] = [1, 4]
#         node['Miami'] = [4]
#         node['Dallas'] = [1, 2, 3]

node = my_connectivity_mat_2_dict(C, names)
    • MATLAB解决方案:**
% Function [node] = myConnectivityMat2Struct(C, names)

function [node] = Chapter5Exercise13(C, names)
% Objective: Construct a Adjacency List from Adjacency Matrix (from nodes of unidirected graph). 
% Input:
%   C - NxN one-directional connectivity  matrix.  
%   names - string array with names of points.  
% Output:
%   node - struct with fields: name and a row vector: neighbors containing indexes j for which C(i, j) = 1.
% Author: Chris B. Kirov
% Date: 30.08.2017      
  
  for i = 1 : length(names)                                    % traverse all names
    
    node(i).name = names(i);                                 % create node; assign name
        
    for j = 1 : size(C, 2)
      
      if (C(i, j) == 1)     
        node(i).neighbors(end + 1) = j;                   % add connected neigbours 
      end
      
    end
        
  end  
    
end
plicqrtu

plicqrtu1#

Python数组从0开始,但在数学和MATLAB中,索引从1开始。这就是为什么在输出中,4有时是正确的答案。
下面是一些Python函数,它们可以满足你的需要:

C = [[0, 1, 0, 1], [1, 0, 0, 1], [0, 0, 0, 1], [1, 1, 1, 0]]                                                                                                                     
names = ['Los Angeles', 'New York', 'Miami', 'Dallas']

# Two loops as in MATLAB
def my_connectivity_mat_2_dict(C, names):
        connections = dict()
        for i, city in enumerate(names):
                connections[city] = []
                for j in range(len(C[i])):
                        if C[i][j]:
                                connections[city].append(j+1)
        return connections

# With a list comprehension
def my_connectivity_mat_2_dict(C, names):
        connections = dict()
        for i, city in enumerate(names):
                connections[city] = [j+1 for j in range(len(C[i])) if C[i][j]]
        return connections

# Even shorter, but hard to understand what it's doing
def my_connectivity_mat_2_dict(C, names):
        return dict((city, [j+1 for j in range(len(C[i])) if C[i][j]]) for i, city in enumerate(names))

node = my_connectivity_mat_2_dict(C, names)
print(node)

相关问题