Python, sum of decimals

Viewed 108

I want to split a string of letters into a bunch of triplets and assign numbers to each triplet and then find the sum of the numbers. I managed to code till the number assigning part. But not able to generate the sum.Lot of errors popping up. Please help. P.S. I am a biologist and know nothing about coding. This is my partial code:

gene_code = "abcdef"

split_strings = []
n  = 3
for index in range(0, len(gene_code), n):
    split_strings.append(gene_code[index : index + n])
print(split_strings)
import re
gene_code = gene_code.replace('abc','1.2,')
gene_code = gene_code.replace('def','2.3,')

print(gene_code)

the output is as follows

['abc', 'def']
1.2,2.3,

Now I want to get the sum of these numbers. Please help?

1 Answers

You could create a dictionary of replacements. Note that the replacements need to be written as numbers, not as strings, to be able to do calculations. Once you have a list of numbers, you can call sum(list_of_numbers).

Here is some example code:

gene_code = "abcdef"
split_strings = [gene_code[i:i + 3] for i in range(0, len(gene_code), 3)]
replacements = {'abc': 1.2, 'def': 2.3}
numbers = [replacements[s] for s in split_strings]
print(sum(numbers))

If some strings don't have a replacement, this code will give an error. You could add a test and replace those numbers with zero instead:

numbers = [0 if not s in replacements else replacements[s]
           for s in split_strings]

Note that the above code uses list comprehension. That way, a loop such as:

new_list = []
for item in old_list:
   new_list.append(func(item))

can be written as

new_list = [func(item) for item in old_list]

Once you're used to that notation, you'll notice it's easier to read and easier to maintain. It gets especially useful when you'd be working with lists of lists.

To read from file:

replacements = {'abc': 1.2, 'def': 2.3}
with open("gene_codes.txt") as file:
    for gene_code in file.readlines():
        gene_code = gene_code.strip()
        # print(gene_code)
        split_strings = [gene_code[i:i + 3] for i in range(0, len(gene_code), 3)]
        numbers = [0 if not s in replacements else replacements[s]
                   for s in split_strings]
        print(sum(numbers))
Related