W
W
wolverine7772021-08-12 00:17:17
Python
wolverine777, 2021-08-12 00:17:17

How to loop adding data from a set to each new element?

Please help with advice - is there any "elegant" way to cycle through adding elements from a set to a sheet? Because the endless nested loops come to my mind just yet.

The bottom line is that I need to get all possible options for a given sequence, for example, there is a pattern: 'ATG' - for it I first need to replace the [0] element - it will turn out:

ATG (here, as it were, replacing A with A)
TTG
GTG
CTG

then you need take ATG (the first of four) and replace the [1] element in it already - it will turn out:

AAG
ATG
AGG
ACG

now ALREADY take AAG in this sheet and replace [2] in it - it will turn out:

AAA
AAT
AAC
AAG

Of course, I showed this only for the first element in each iteration - in the end, I need to go through all the elements of the sheet in each iteration in this way and for each replace the subsequent letter that corresponds to the iteration number.

If there is only one letter, there will be 4 options, if 2 - 16, respectively, and so on (4**n)

so far, this solution seems to me the only way: but something tells me that this is bullshit.

pat = 'ATG'
tst = list(pat)

for i in range(len(tst)):
    
    for y in {'A','T','G','C'}:
        tst[i]=y
        print(tst)
        tst = list(pat)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-08-12
@sergiks

All possible combinations with repetitions, length 3:

from itertools import product 
for s in product('ATGC', repeat=3):
    print(s)
'''
('A', 'T', 'G')
('A', 'T', 'C')
('A', 'G', 'A')
('A', 'G', 'T')
('A', 'G', 'G')
...
'''

itertools.product()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question