Reputation: 7
My question is: how I can define an input code that the user can be entered for example 3, 5, 6, or any number to get an output with 3 letters, 5 letters and etc(according to user input).
Output for this code is:
TC:2,
CG:2,
AT:3,
GC:1,
CA:1,
GA:1,
Code:
dna = "ATCGCATCGAT"
bases = ['A', 'C', 'G', 'T']
all_counts = {}
for base1 in bases:
for base2 in bases:
dinucleotide = base1 + base2
count = dna.count(dinucleotide)
if count > 0:
all_counts[dinucleotide] = count
for key, value in all_counts.items():
print(key, ':', value)
If the user entered 3, that code will be change like:
output for number 3 is:
ATC : 2,
CAT : 1,
CGA : 1,
CGC : 1,
GAT : 1,
GCA : 1,
TCG : 2,
dna = "ATCGCATCGAT"
bases = ['A', 'C', 'G', 'T']
all_counts = {}
for base1 in bases:
for base2 in bases:
for base3 in bases:
dinucleotide = base1 + base2 + base3
count = dna.count(dinucleotide)
if count > 0:
all_counts[dinucleotide] = count
for key, value in all_counts.items():
print(key, ':', value)
So, my question is:
How with user input, we can control or add a new loop to this code?
For example, if user entered 4, the program added a new loop automatically by splitting the letter in 4 with this output:
ATCG : 2,
CATC : 1,
CGAT : 1,
CGCA : 1,
GCAT : 1,
TCGA : 1,
TCGC : 1,
Upvotes: 0
Views: 261
Reputation: 121
Since you’re trying to get all the permutations of given list taken n at a time where n is input by user, instead of using for loops try permutation function . The permutations function gives a list of tuples containing each permutations taken n at a time
from itertools import permutations
n=int(input(“enter the value of n”))
dna = "ATCGCATCGAT"
bases = ['A', 'C', 'G', 'T']
perm = permutations(bases, n)
all_counts = {}
for i in list(perm):
dinucleotide= ''.join(i)
count = dna.count(dinucleotide)
if count > 0:
all_counts[dinucleotide] =count
for key, value in all_counts.items():
print(key, ':', value)
Upvotes: 1
Reputation: 2133
Something like this?
dna = "ATCGCATCGAT"
#print(dna)
sub_len = int(input('enter len: '))
combis = set()
for pos in range(len(dna) - sub_len + 1):
sub_str = dna[pos:pos + sub_len]
combis.add(sub_str)
for combi in combis:
print(combi, dna.count(combi))
print(combis)
Output:
enter len: 4
TCGC 1
CATC 1
TCGA 1
ATCG 2
GCAT 1
CGCA 1
CGAT 1
{'TCGC', 'CATC', 'TCGA', 'ATCG', 'GCAT', 'CGCA', 'CGAT'}
Upvotes: 0
Reputation: 39
I think you can put the logic of the inner-most loop in a function and then call that function based on the input. Alternatively, you can try to solve the same problem with recursion, wherein the user-input would define the recursion depth. Initialize a global variable depth and set that to 0. In the first line of the function, increment depth with 1 and every time the function will be called, it's value will be increased. In the base case, set a condition for the depth variable and the input variable to be equal, as soon as the depth variable == the input variable, the recursion will stop.
Upvotes: 0