Generating a pair of letter from a given sequence
Question:
I have a problem to be solved and I would appreciate if anyone can help. I want to generate all possible two-letters string from the given sequence. For example from string ‘ACCG’, I want to generate a list of [AA, CC, GG, AC,CA,AG,GA,CG,GC].
Does anyone have an idea how I can do that ?
Answers:
An efficient solution can be coded using itertools
module
CODE
import itertools
string = 'ACCG'
num = 2
combinations = list(itertools.product(string, repeat=num))
result = [*set([''.join(tup) for tup in combinations])]
print(result)
OUTPUT
['CG', 'GG', 'GC', 'GA', 'AG', 'AA', 'CC', 'AC', 'CA']
If you want a one-liner (using product from itertools) then try this:
from itertools import product
out = [''.join(p) for p in set(product('ACCG', repeat=2))]
print(out)
Output:
['AA', 'GG', 'CC', 'GA', 'AC', 'CG', 'GC', 'CA', 'AG']
I have a problem to be solved and I would appreciate if anyone can help. I want to generate all possible two-letters string from the given sequence. For example from string ‘ACCG’, I want to generate a list of [AA, CC, GG, AC,CA,AG,GA,CG,GC].
Does anyone have an idea how I can do that ?
An efficient solution can be coded using itertools
module
CODE
import itertools
string = 'ACCG'
num = 2
combinations = list(itertools.product(string, repeat=num))
result = [*set([''.join(tup) for tup in combinations])]
print(result)
OUTPUT
['CG', 'GG', 'GC', 'GA', 'AG', 'AA', 'CC', 'AC', 'CA']
If you want a one-liner (using product from itertools) then try this:
from itertools import product
out = [''.join(p) for p in set(product('ACCG', repeat=2))]
print(out)
Output:
['AA', 'GG', 'CC', 'GA', 'AC', 'CG', 'GC', 'CA', 'AG']