I have recently answered one question on Stack Overflow.
Problem statement:
Input sequence:
PEACCEL
User mutation input file:
E2R C4W E6G
The algorithm is for an input sequence of, say, PEACCEL and mutation E2R. We need to replace second character in sequence, that is, E to R, and so on for the combinations of mutations.
I provided this answer:
from itertools import combinations,chain
from collections import Counter
input_sequence='PEACCEL'
mutations=map(lambda x:x.strip(),open('a.txt','r').readlines())
#['E2R', 'C4W', 'E6G']
mutation_combinations= chain.from_iterable([list(combinations(mutations,i))for i in range(1,4)])
#[('E2R',), ('C4W',), ('E6G',), ('E2R', 'C4W'), ('E2R', 'E6G'), ('C4W', 'E6G'), ('E2R', 'C4W', 'E6G')]
for i in mutation_combinations:
print "combination :"+'_'.join(i)
c=Counter({})
temp_string=input_sequence
for j in i:
c[j[1]]=j[2].lower()
for index,letter in c.items():
temp_string=temp_string[:int(index)-1]+letter+temp_string[int(index):]
print temp_string
Output:
combination :E2R PrACCEL combination :C4W PEAwCEL combination :E6G PEACCgL combination :E2R_C4W PrAwCEL combination :E2R_E6G PrACCgL combination :C4W_E6G PEAwCgL combination :E2R_C4W_E6G PrAwCgL
Algorithm I followed:
Read the mutation sequences like E2R.... from a file using
mutations=map(lambda x:x.strip(),open('a.txt','r').readlines())
Made the combinations of the mutations
mutation_combinations= chain.from_iterable([list(combinations(mutations,i))for i in range(1,4)])
If you have 4 mutations you want all four change the
range value to 5
.For each combination I replaced them with specified character:
for j in i: c[j[1]]=j[2].lower()
I used the above counter to keep track of which character was to be replaced during the mutation combination.
How can I make this more efficient? I also need to know of any valuable pointers I should know while coding.
C4W_E6G
createsPEAwCgL
instead ofPEAWCGL
. \$\endgroup\$