你的程序逻辑确实有点不对劲。这是一个版本,它可以满足我的理解你想要的:
import numpy as np
import networkx as nx
from networkx.algorithms.isomorphism import GraphMatcher
def brute_force_find_iso_pair(shape, maxiter, template=None):
def make_random_graph():
return nx.Graph(np.random.random_integers(0, 1, shape))
G4 = make_random_graph() if template is None else template
def check_iso(G5):
return GraphMatcher(G4, G5).is_isomorphic()
for n in range(maxiter):
G5 = make_random_graph()
if check_iso(G5):
break
else:
G5 = None
return G4, G5, n + 1
# example
G4, G5, n = brute_force_find_iso_pair((4, 4), 50)
print(f"""After {n} iterations:
template: {G4.adj}
match: {G5 and G5.adj}
""")
样品运行:
After 43 iterations:
template: {0: {1: {'weight': 1}, 3: {'weight': 1}, 2: {'weight': 1}}, 1: {0: {'weight': 1}, 1: {'weight': 1}, 2: {'weight': 1}, 3: {'weight': 1}}, 2: {1: {'weight': 1}, 0: {'weight': 1}, 2: {'weight': 1}, 3: {'weight': 1}}, 3: {0: {'weight': 1}, 1: {'weight': 1}, 2: {'weight': 1}}}
match: {0: {2: {'weight': 1}, 1: {'weight': 1}, 3: {'weight': 1}}, 1: {0: {'weight': 1}, 3: {'weight': 1}, 2: {'weight': 1}}, 2: {0: {'weight': 1}, 1: {'weight': 1}, 2: {'weight': 1}, 3: {'weight': 1}}, 3: {1: {'weight': 1}, 0: {'weight': 1}, 2: {'weight': 1}, 3: {'weight': 1}}}
After 50 iterations:
template: {0: {1: {'weight': 1}, 2: {'weight': 1}}, 1: {0: {'weight': 1}, 3: {'weight': 1}, 2: {'weight': 1}}, 2: {0: {'weight': 1}, 1: {'weight': 1}, 3: {'weight': 1}}, 3: {1: {'weight': 1}, 2: {'weight': 1}}}
match: None
After 25 iterations:
template: {0: {1: {'weight': 1}, 3: {'weight': 1}, 2: {'weight': 1}}, 1: {0: {'weight': 1}, 2: {'weight': 1}}, 2: {1: {'weight': 1}, 0: {'weight': 1}, 2: {'weight': 1}}, 3: {0: {'weight': 1}}}
match: {0: {1: {'weight': 1}}, 1: {0: {'weight': 1}, 2: {'weight': 1}, 3: {'weight': 1}}, 2: {1: {'weight': 1}, 2: {'weight': 1}, 3: {'weight': 1}}, 3: {1: {'weight': 1}, 2: {'weight': 1}}}
After 2 iterations:
template: {0: {0: {'weight': 1}, 2: {'weight': 1}, 3: {'weight': 1}}, 1: {2: {'weight': 1}, 3: {'weight': 1}}, 2: {0: {'weight': 1}, 1: {'weight': 1}, 2: {'weight': 1}, 3: {'weight': 1}}, 3: {0: {'weight': 1}, 1: {'weight': 1}, 2: {'weight': 1}}}
match: {0: {2: {'weight': 1}, 3: {'weight': 1}}, 1: {1: {'weight': 1}, 2: {'weight': 1}, 3: {'weight': 1}}, 2: {0: {'weight': 1}, 1: {'weight': 1}, 3: {'weight': 1}}, 3: {0: {'weight': 1}, 1: {'weight': 1}, 2: {'weight': 1}, 3: {'weight': 1}}}
After 32 iterations:
template: {0: {2: {'weight': 1}, 3: {'weight': 1}}, 1: {2: {'weight': 1}, 3: {'weight': 1}}, 2: {1: {'weight': 1}, 0: {'weight': 1}, 3: {'weight': 1}}, 3: {1: {'weight': 1}, 2: {'weight': 1}, 0: {'weight': 1}}}
match: {0: {1: {'weight': 1}, 2: {'weight': 1}, 3: {'weight': 1}}, 1: {0: {'weight': 1}, 2: {'weight': 1}}, 2: {0: {'weight': 1}, 1: {'weight': 1}, 3: {'weight': 1}}, 3: {0: {'weight': 1}, 2: {'weight': 1}}}