【问题标题】:How to control the number of loops with user input?如何通过用户输入控制循环次数?
【发布时间】:2020-10-25 16:38:04
【问题描述】:

我的问题是:如何定义用户可以输入的输入代码,例如 3、5、6 或任何数字,以获得 3 个字母、5 个字母等的输出(根据用户输入)。

这段代码的输出是:

TC:2,
CG:2,
AT:3,
GC:1,
CA:1,
GA:1,

代码:

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)

如果用户输入 3,则该代码将更改为:
数字 3 的输出是:

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)

所以,我的问题是:
我们如何通过用户输入来控制或添加新循环到这段代码?
例如,如果用户输入 4,程序会自动添加一个新循环,将字母分成 4 并输出如下:

ATCG : 2,
CATC : 1,
CGAT : 1,
CGCA : 1,
GCAT : 1,
TCGA : 1,
TCGC : 1,  

【问题讨论】:

  • 您好,您尝试if 声明了吗?在我写答案之前,我认为if 是你想要的。对吗?
  • 你好,其实这段代码需要定义一个输入,我需要和用户交互。
  • 你想用len n计算a(ny)子串的出现次数,其中n是用户输入的吗?
  • 是的,确实,根据输入的数字,组成多少个字母组合。输出应该和例子一样。

标签: python for-loop input


【解决方案1】:

由于您试图在用户输入 n 时获取给定列表的所有排列 n ,而不是使用 for 循环尝试 permutation function 。 permutations 函数给出了一个元组列表,其中包含一次 n 个排列的每个排列

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)


          

【讨论】:

    【解决方案2】:

    这样的?

    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)
    

    输出:

    enter len: 4
    TCGC 1
    CATC 1
    TCGA 1
    ATCG 2
    GCAT 1
    CGCA 1
    CGAT 1
    {'TCGC', 'CATC', 'TCGA', 'ATCG', 'GCAT', 'CGCA', 'CGAT'}
    

    【讨论】:

      【解决方案3】:

      我认为您可以将最内层循环的逻辑放在一个函数中,然后根据输入调用该函数。或者,您可以尝试使用递归解决相同的问题,其中用户输入将定义递归深度。初始化一个全局变量 depth 并将其设置为 0。在函数的第一行,将 depth 增加 1,每次调用该函数时,它的值都会增加。在基本情况下,设置深度变量和输入变量相等的条件,只要深度变量==输入变量,递归就会停止。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-16
        • 1970-01-01
        • 2012-02-25
        • 2021-12-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多