【问题标题】:Python - multiple combinations maths questionPython - 多重组合数学题
【发布时间】:2019-12-06 00:21:15
【问题描述】:

我正在尝试制作一个程序,列出 DNA 的所有 64 个密码子/三联体碱基序列...... 在更数学的术语中,有 4 个字母:A、T、G 和 C。

我想列出所有可能的结果,其中每个字母有三个字母,一个字母可以多次使用,但我不知道怎么用!

我知道有 64 种可能性,我将它们全部写在纸上,但我想编写一个程序来为我生成所有这些可能性,而不是我输入全部 64 种可能性!

目前,我处于这一点,但我肯定把它复杂化了,我被困住了:

list = ['A','T','G','C']

list2 = []

y = 0

x = 1

z = 2

skip = False

back = False

for i in range(4):

 print(list[y],list[y],list[y])

  if i == 0:

   skip = True

  else:

    y=y+1

  for i in range(16):

    print(list[y],list[y],list[x])

    print(list[y],list[x], list[x])

    print(list[y],list[x], list[y])

    print(list[y],list[x], list[z])

   if i == 0:

      skip = True

  elif z == 3:

      back = True

      x = x+1

    elif back == True:

      z = z-1

      x = x-1

    else:

      x = x+1

      z = z+1

任何帮助将不胜感激!!!!

【问题讨论】:

  • 你是对的,你的代码看起来确实过于复杂!尝试制作 3 个循环,一个用于三联体中的每个位置。请记住在每个循环中使用不同的索引,例如i 作为第一个循环的索引,j 用于第二个循环,k 用于第三个循环。
  • [''.join(p) for p in itertools.product('ATCG',repeat = 3)]

标签: python math combinations


【解决方案1】:

你真的应该为此使用itertools.product

from itertools import product

l = ['A','T','G','C']

combos = list(product(l,repeat=3 ))
# all 64 combinations

由于这会产生一个迭代器,因此如果您只是要循环遍历它,则无需将其包装在 list() 中。 (另外,不要将您的列表命名为 list — 它会破坏内置)。

如果您想要一个字符串列表,您可以join() 它们,正如 John Coleman 在您问题下方的评论中所显示的那样。

list_of_strings = ["".join(c) for c in product(l,repeat=3) ]

【讨论】:

    【解决方案2】:

    寻找具有重复性的 pemuations,那里有大量可用于 Python 的代码。 如果你想看看他们是如何实现它的,我会使用库。这些家伙通常做得非常有效率

    import itertools
    x = [1, 2, 3, 4, 5, 6]
    [p for p in itertools.product(x, repeat=2)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      相关资源
      最近更新 更多