vendredi 18 décembre 2020

Value that was calculated in the beginning of a function isn't remembered later on in the same function

In the beginning of the function I calculate the total weight of a protein sequence and define it as seq_weight. After that I calculate the weight of several fragments and make combinations of those weights that sum to the total weight of the first proteins sequence. The first print statement prints the total weight correctly, but near the end of the function it seems to forget that value when I want to define it as the result of the sum.

When I type the value manually I get the result I want:

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)

This is the result:

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 I write

if sum(item) == seq_weight:

the result doesn't print the combination of weights like I intended.

Sorry if the code is kind of messy, I'm still a beginner.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire