我有一系列的元素:
A111 T112 I113 A114 S115 I116 D117 F118 K119 R120 E121 T122 C123 V124 V125 V126 T112
在约束下,每个元素只出现一次在上述序列中,t112发生两次。因此,我需要创建满足约束的所有可能子序列,即:
T112 I113 A114 S115 I116
I116 K119 R120 E121 T122 C123 V124 V125 V126 T112
在更复杂的场景中,我有以下序列必须满足相同的约束:
A111 T112 I113 A114 T112 S115 I116 D117 I116 K119 R120 E121 T122 C123 V124 V125 V126
这一次T112也发生了两次I116在这种情况下,我需要以下子序列:
A111 T112 I113 A114
I113 A114 T112 S115 I116 D117
D117 I116 K119 R120 E121 T122 C123 V124 V125 V126
当然,一个元素可能出现两次以上。在不使用遗传算法的情况下,有什么有效的方法来解决这个问题吗?

最佳答案

代码:

list  = ["A111", "T112", "I113", "A114", "T112", "S115", "I116", "D117", "I116", "K119", "R120", "E121", "T122", "C123", "V124", "V125", "V126"]

subsequence = []
for item in list:
    if item in subsequence:
        print subsequence
        index = subsequence.index(item)+1
        subsequence = subsequence[index:]
    subsequence.append(item)
print subsequence

将打印:
['A111', 'T112', 'I113', 'A114']
['I113', 'A114', 'T112', 'S115', 'I116', 'D117']
['D117', 'I116', 'K119', 'R120', 'E121', 'T122', 'C123', 'V124', 'V125', 'V126']

09-03 20:04