2011-10-07 91 views
1

这是由我的教授发布并由学生修改的群体遗传学程序。Python 2.7:L + = branch_length导致NameError:name'L'未定义

基本上它应该用给定的样本,总体和突变率(u)来模拟20次预期的突变数。然而,关键部分是总分支长度(L),它是各种较小分支长度(分支长度)的总和。然而,当我如下定义L,它不断回来,出现错误:

L += branch_length 
NameError: name 'L' is not defined 

我不知道什么是错的,因为tree_depth是指以同样的方式和完美的作品。

下面是完整的代码:

from random import expovariate 
from pgen import poidev 
K = 77  # sample size (number of gene copies) 
twoN = 5000 # population size 
u = .001 

tree_depth = 0.0 # age of last common ancestor in generations 

# Each pass through loop deals with one coalescent interval. 

for A in range(20): 
    while K > 1: 
     h = K*(K-1)/(2.0*twoN) # hazard of a coalescent event 
     t = expovariate(h)  # time until next coalescent event 
     tree_depth += t 
     branch_length = t*K 
     K -= 1 
     L += branch_length 
    S = poidev(u*L) 
    print "Simulation:", A+1, "Total Mutations:", S 
print "Total tree depth (L):", L, "generations" 

我只是失去了一些东西真的,真的很明显?提前致谢。

回答

4

L += x将x添加到现有L中,但是您尚未初始化L.推测,您希望L = 0位于文件顶部的某个位置。

+0

工作就像一个魅力。我知道这很简单。 谢谢! – user984748

1

在做L += x之前,您需要定义L = 0

一般来说,修改前需要定义变量。对于赋值,不存在任何问题,因为python会为你推断类型。

一些例子:

>>> a += 0 #Invalid 
Traceback (most recent call last): 
    File "<input>", line 1, in <module> 
NameError: name 'a' is not defined 
>>> a = 5 #Valid 
>>> a += 0 #Now it's valid, because a is defined. 
>>> 
>>> my_list.append(5) #Invalid 
Traceback (most recent call last): 
    File "<input>", line 1, in <module> 
NameError: name 'my_list' is not defined 
>>> my_list = [] 
>>> my_list.append(5) #Now valid 
>>> my_list 
[5] 
>>> 
>>> my_list2 = [1, 2, 3, 4] #Valid, because it's an assignment.