首页 > 解决方案 > 在函数开始时计算的值稍后不会在同一函数中记住

问题描述

在函数的开头,我计算蛋白质序列的总重量并将其定义为 seq_weight。之后,我计算了几个片段的重量,并将这些重量组合在一起,总和为第一个蛋白质序列的总重量。第一个打印语句正确打印总重量,但在函数结束时,当我想将其定义为总和的结果时,它似乎忘记了该值。

当我手动输入值时,我得到了我想要的结果:

def fragmentcombinations(sequence, fragments):                                                        
  for seq_rec in sequence: 
    seq_weight = 0.0                                                                                                
    for i in seq_rec.seq:                                            
      seq_weight += SeqUtils.molecular_weight(i, "protein")
    print("The protein sequence: " + seq_rec.seq)
    print("The molecular weight: " + str(round(seq_weight, 2)) + " Da.") 
    nums = []
    for a in fragments:                                                   
      fragment_weights = 0.0                                                              
      for aa in a.seq:                                                    
        fragment_weights += SeqUtils.molecular_weight(aa, 'protein')
      nums.append(round(fragment_weights, 2))
    print(nums)
    weights_array = []
    combs = []
    if len(nums) > 0:                                                     
      for r in range(0,len(nums)+1):        
          weights_array += list(combinations(nums, r))
      for item in weights_array:        
          if sum(item) == 4364.85:   #Sequence weight needs to inserted manually -> not ideal
              combs.append(item)
    print(" ")
    print("The possible combinations of fragment weights that may cover the protein sequence without overlap are: ")
    for row in combs:
      print(*row, sep = ", ") 

fragmentcombinations(seq_list3, seq_list4)

这是结果:

The protein sequence: IEEATHMTPCYELHGLRWVQIQDYAINVMQCL
The molecular weight: 4364.85 Da.
[3611.86, 2269.63, 469.53, 556.56, 1198.41, 2609.88, 547.69, 1976.23, 2306.48, 938.01, 1613.87, 789.87, 737.75, 2498.71, 2064.25, 1184.39, 1671.87]
     
The possible combinations of fragment weights that may cover the protein sequence without overlap are: 
556.56, 1198.41, 2609.88
469.53, 2609.88, 547.69, 737.75
556.56, 1198.41, 938.01, 1671.87
469.53, 547.69, 938.01, 737.75, 1671.87

如果我写

if sum(item) == seq_weight:

结果不会像我想要的那样打印权重组合。

对不起,如果代码有点乱,我还是个初学者。

提前致谢!

标签: functionfor-loopif-statementsumbiopython

解决方案


问题不在于您的变量不再被记住。问题是您在浮点数之间执行精确比较。在编程浮点数是“十进制”数字,但它们不是数字的精确表示。它们只能达到任意精度。

让我们做一些基本的数学 Python。

>>> a = 0.2 + 0.1
>>> a
0.30000000000000004
>>> a == 0.3
False

如您所见,这里显然发生了一些奇怪的事情。但这正是浮点运算的工作原理。


现在我们已经解释过了。你应该怎么做才能让你的程序正常工作?有多种解决方案。

处理它的一种方法是将您的数字与一些固定的差异进行比较。IE

if abs(sum(item) - seq_weight) < 0.00001

解决这个问题的另一种方法是使用固定精度的十进制对象,但这可能比您想象的要困难。https://docs.python.org/3/library/decimal.html


推荐阅读