from numpy import *
import numpy
import random
import itertools
def check(v): #判断是否是回路
i3,i4,i5,i6=0,0,0,0
t=1
c= numpy.zeros((m, n)) #创建一个与电路矩阵相同大小的零矩阵
for i3 in v:
c[:, int(i3)] = a1[:, int(i3)]
for i4 in range(m): #将后面所有列的元素与全部加到第一列
for i5 in range(n-1):
c[i4,0]+= c[i4,i5+1]
for i6 in range(m): #判断第一列是都有0元素
if c[i6,0]==0:
t=0
break
if t==1:
return 1 #无0即不是回路,返回1 输出
else:
return 0 #有0即是回路,返回0 不输出输出
def C(n,i): #确定组合个数
#n>=i
Min=min(i,n-i)
result=1
for j in range(0,Min):
result=result*(n-j)/(Min-j)
return result
#电路图定义部分
if __name__ == '__main__':
m = int(input("请输入节点数"))
n = int(input("请输入支路数"))
i = 0
j = 0
c = 0
count = 0
shu_num=0
input1 = list(input("请输入电路图对应矩阵"))
for c in range(m - 1):
input1.remove(' ') #移除字符串中的空格键
q = list(input1)
a1 = numpy.zeros((m, n))
for i in range(m):
for j in range(n):
a1[i,j] = int(q[count]) #将list中的每一个元素分别给矩阵按行赋值
count += 1
list1 = []
b=[]
for i in range(n):
list1.append(i) #list1存放1-n个数用来产生所有组合
list2 = list(itertools.combinations(list1, m-1))
num = int(C(n, m - 1)) #调用C函数
for i in range (num):
if check(list2[i])==1: #调用check 检查是否是回路函数
shu_num+=1
b = [m + 1 for m in list2[i]]
print("该电路图的树",shu_num,b)
代码验证: