import copy
import networkx as nx
import random
def IC_Model(graph,seeds):
active_node = copy.deepcopy(seeds)#深拷贝,修改新的不会影响旧的
for seed in seeds:
graph.nodes[seed]["state"]=1#将种子节点中的状态置为1
neighbor_nodes =graph[seed]#种子节点的邻居节点
for neighbor in neighbor_nodes:#遍历邻居节点
wei =graph.get_edge_data(seed,neighbor)#返回与边(seed,neighbor)关联的属性字典
if graph.nodes[neighbor]["state"]==0 and wei["weight"] >random.uniform(0,1):
graph.nodes[neighbor]["state"]=1
active_node.append(neighbor)
return len(active_node)
def greedy(graph ,k):
while k>len(seeds):
max_influence = 0
for node in g.nodes:
if node not in seeds :
node_list=[]
node_list.append(node)
increase = IC_Model(g, node_list)
node_list.pop()
if increase>max_influence:
max_node = node
max_influence =increase
seeds.append(max_node)
print(seeds)
if __name__ =='__main__':
g =nx.karate_club_graph()
for edge in g.edges:
g.add_edge(edge[0], edge[1], weight=random.uniform(0, 1))
for node in g.nodes:
g.add_node(node, state=0)
seeds=[1,2]
greedy(g,5)
1.关于列表赋值:a(列表)=b(列表)将b赋值给a,a、b指向一个同一列表,产生一个引用,内存地址相同。深拷贝:创造一个一模一样的对象,新对象跟原对象不共享内存,修改新对象不会改到原对象