peter cai
peter cai

Reputation: 113

How to implement n times nested loops in python?

I want to do nested loops with n times, this n is an variable and can be provided by function or input methods. In order to do this, I have to write lots of if..elif blocks depend on size of n, does anybody have good strategies to handle this task? The codes (for combination of 4 letters problem) I used are as follows:

def charCombination(n):
   patList = []
   s = 'ATCG'
   if n == 1:
       for i in s:
           patList.append(i)
   elif n == 2:
       for i in s:
           for j in s:
               patList.append(i+j)
   elif n == 3:
       for i in s:
           for j in s:
               for k in s:
                   patList.append(i+j+k)
   ...

   return patList

Upvotes: 1

Views: 1115

Answers (1)

thefourtheye
thefourtheye

Reputation: 239493

You can use itertools.product with repeat parameter

import itertools

def charCombination(n):
    return ["".join(item) for item in itertools.product("ATCG", repeat=n)]

print charCombination(1)
print charCombination(2)
print charCombination(3)

Output

['A', 'T', 'C', 'G']
['AA', 'AT', 'AC', 'AG', 'TA', 'TT', 'TC', 'TG', 'CA', 'CT', 'CC', 'CG', 'GA', 'GT', 'GC', 'GG']
['AAA', 'AAT', 'AAC', 'AAG', 'ATA', 'ATT', 'ATC', 'ATG', 'ACA', 'ACT', 'ACC', 'ACG', 'AGA', 'AGT', 'AGC', 'AGG', 'TAA', 'TAT', 'TAC', 'TAG', 'TTA', 'TTT', 'TTC', 'TTG', 'TCA', 'TCT', 'TCC', 'TCG', 'TGA', 'TGT', 'TGC', 'TGG', 'CAA', 'CAT', 'CAC', 'CAG', 'CTA', 'CTT', 'CTC', 'CTG', 'CCA', 'CCT', 'CCC', 'CCG', 'CGA', 'CGT', 'CGC', 'CGG', 'GAA', 'GAT', 'GAC', 'GAG', 'GTA', 'GTT', 'GTC', 'GTG', 'GCA', 'GCT', 'GCC', 'GCG', 'GGA', 'GGT', 'GGC', 'GGG']

Upvotes: 6

Related Questions