有A,T,C,G四个字符串,一共有6个位置,每个位置可以填四个中的任意一个,输出所有的组合。
1,递归输出。
1 | def permutations(n,s=''): |
1 | 2,利用itertools。 |
from itertools import combinations, permutations
combinations([1,2,3,4,5],2)
<itertools.combinations object at 0x10469a650>
[i for i in combinations([1,2,3,4,5],2)]
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
[i for i in permutations([1,2,3,4,5],2)]
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4)]
1 | ``` |
3,变化进制加法实现。
比如,求10位每位上有两种选择,0或1,的所有排列组合,这个时候我们只需遍历一遍0到1024(2的10次方),0,1,10,11,100,……。再在前面补充0使字符串的总长度为10,是不是就可以得倒所有的排列组合了吗?
和这一道题同理,只不过这道题是4进制(0,1,2,3分别代表ATCG)。
1 | def Permutations(max_len): |
其中,数组singles为每个位置可以放的字符串集合,max_len为字符串的位数。Permutations(6)
即可调用。