当前位置: 代码迷 >> python >> 对代码和变量使用字典
  详细解决方案

对代码和变量使用字典

热度:115   发布时间:2023-07-16 09:57:03.0

我有以下代码终于可以工作了! 但是,作为Python新手,我想看看是否有更好的方法可以做到这一点。 特别地,作为蒙特卡洛化学动力学项目的一部分,底部的循环必须确实非常快。 应该快吗? 是否有比将所有内容捆绑在字典中更好(更Python化)的方法? 这些词典可能有多达数百个条目。 谢谢!

def split(pops,src, dst): pops[src] -= 1; pops[dst] += 2
def join(pops,src, dst) : pops[src] -= 1; pops[dst] += 2
def jump(pops,src, dst) : pops[src] -= 1; pops[dst] += 2

j1, j2, s1, s2, m1, m2, d1, d2 = .1, .1, .1, .1, .1, .1, .1, .1

pops = {'mon1':1000,    # initial population of monomers in regime 1
        'dim1':1000,    #        "              dimers   "
        'mon2':1000,    # etc.
        'dim2':1000}

trns = {'j1':(j1, join, 'mon1', 'dim1'),  # j1=prob of 2 monomers joining to form a dimer
        'j2':(j2, join, 'mon2', 'dim2'),  
        's1':(s1, split,'dim1', 'mon1'),
        's2':(s2, split,'dim2', 'mon2'),
        'm1':(m1, jump ,'mon1', 'mon2'),
        'm2':(m2, jump ,'mon2', 'mon1'),
        'd1':(d1, jump ,'dim1', 'dim2'),
        'd2':(d2, jump ,'dim2', 'dim1')}    

while True: 
    event = 's1' # this would be derived from rand(), called many times

    action  = trns[event][1]   # either join, split or jump
    source  = trns[event][2]   # source species
    dest    = trns[event][3]   # destination species

    action(pops, source, dest) # make the function call to update populations
    break

print pops

您可能会发现,使用已经过优化以有效地进行优化的库,可以更轻松地进行Monte Carlo仿真,从而可以在问题域而不是在python代码编写域中直接进行工作。 例如,参见python库scipy中的Monte Carlo。

  相关解决方案