Loading

递归生成10bpDNA

前面

运用递归生成10bp所有可能的DNA序列,即由A,T,G,C组成的所有长度为10的字符串。一个位置有4种可能,一共存在有 4^10 = 1048576可能的字符串。

递归

递归之前已经写过可以查看汉诺塔游戏的递归解析。看了这篇文章,再来琢磨下能不能自己写出代码。能写出来,代表你理解了~。

代码

这里提供PythonC两个语言的代码。经过比较,C的代码比Python的快的很多~

Python
import sys
sys.setrecursionlimit(1048577) # Python默认允许的递归深度为1000,需要重新设置一下。

L = 10
base = ["A", "T", "G", "C"]
dna_seq = ["N"] * 10 

def DNA(handle, idx):
	idx += 1
	for N in base:
		if idx < L:
			dna_seq[idx] = N
			DNA(handle, idx)
		else:
			seq = "".join(dna_seq)
			handle.write(seq)
			handle.write("\n")
			return 0

def main():
	with open("DNA_10bp.txt", "w") as f:
		idx = -1
		DNA(f, idx) 

main()
C
#include <stdio.h>
#include <stdlib.h>

int DNA(FILE *fp, int idx)
{
    static char base[] = {'A', 'T', 'G', 'C', '\0'};
    static char dna[12];
    idx++;
    for (int i = 0; i < 4; i++)
    {
        if (idx < 11)
        {
            dna[idx - 1] = base[i];
            DNA(fp, idx);
        }
        else
        {
            dna[idx-1] = '\n';
            dna[idx + 1] = '\0';
            fputs(dna, fp);
            return 0;
        }
    }
    return 0;
}

int main()
{
    FILE *fp;
    int idx = 0;
    fp = fopen("DNA_10bp.fasta", "w");
    DNA(fp, idx);
    fclose(fp);
    return 0;
}
posted @ 2019-10-16 20:43  何物昂  阅读(534)  评论(1编辑  收藏  举报