首页 > 解决方案 > 想要迭代一个函数 10 次,并取其值的平均值(python)

问题描述

我有一个有 4 个参数的函数,我想迭代这个函数 10 次,并将那个计数器作为函数的参数。这是我要迭代的函数:

np.random.seed(1)  
def  propagate ( seed ,  network ,  threshold ,  steps ): 
      "" "Start cascade from node` seed` of network `net`." "" 
      activated  =  [ seed ] 
      pocket  =  [ seed ] 
      exposition  =  {} 
      time  =  0 
      while  time  <  steps : 
          time  +=  1 
          # propagate 
          for  seed  in  pocket : 
              for  out_node  in  network . successors( seed ): 
                  add_weight  =  network [ seed ] [ out_node ] [ "weight" ] 
                  if  out_node  not  in  activated : 
                      if  out_node  in  exposition : 
                          exposition [ out_node ]  +=  add_weight 
                      else : 
                          exposition [ out_node ]  =  add_weight 
          # activate 
          pocket  =  [] 
          for  node ,  total  in  exposition .items (): 
              if  total  =  threshold : 
                  pocket . append ( node ) 
         activated  +=  pocket [:] 
         for  node  in  pocket : 
             del  exposition [ node ] 
     return  len ( activated )z

我想选择 10 个节点,网络是一个存储的图形,迭代(参数是步骤)它 5 次,阈值具有 1-5 的值,并计算激活节点的平均数量。这是我尝试过的。它不多,但我也不明白它应该如何工作。

act_nodes=[]  
for i in range(1,5):
    propagate(1,B,5,i)
    act_nodes.append(propagate)

标签: pythonfunctionloops

解决方案


您应该附加函数的结果:

 act_nodes=[] 
 for i in range(1,5):
     x=propagate(1,B,5,i)
     act_nodes.append(x)

“激活”在函数内部声明并且不在函数外部,这是错误的。另外,为什么要在范围(1,5)中循环?这将运行 4 次,但您说需要 10 次?


推荐阅读