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 ?

Asked By: n.oxa

||

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']
Answered By: vignesh kanakavalli

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']
Answered By: Vlad
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.