python中实现查找NDA的motif

 

给定两个字符串str1和str2,返回字符串str2在str1中的所有的位置索引。 

001、 直接实现

[root@pc1 test01]# ls
test.py
[root@pc1 test01]# cat test.py     ## 程序
#!/usr/bin/env python
# -*- coding: utf-8 -*-

str1 = "GATATATGCATATACTT"       ## 在str1中查找str2,返回索引
str2 = "ATAT"

list1 = list()
for i in range(len(str1)):
        idx = str1.find(str2,i)
        if idx != -1 and i == idx:
                list1.append(idx + 1)
print(list1)
[root@pc1 test01]# python3 test.py    ## 结果
[2, 4, 10]

 

002、函数结构实现

[root@pc1 test01]# ls
test.py
[root@pc1 test01]# cat test.py             ## 程序
#!/usr/bin/env python
# -*- coding: utf-8 -*-

str1 = "GATATATGCATATACTT"
str2 = "ATAT"

def motif(x,y):
        list1 = []
        for i in range(len(x)):
                idx = x.find(y,i)
                if idx != -1 and idx == i:
                        list1.append(i + 1)
        return list1
print(motif(str1,str2))
[root@pc1 test01]# python test.py          ## 结果
[2, 4, 10]

 

解法2

003、

[root@pc1 test01]# ls
test.py
[root@pc1 test01]# cat test.py          ## 检索程序
#!/usr/bin/env pyhton
# -*- coding: utf-8 -*-

str1 = "GATATATGCATATACTT"
str2 = "ATAT"

list1 = list()
idx = str1.find(str2)

while idx != -1:
        list1.append(idx + 1)
        idx = str1.find(str2, idx + 1)

print(list1)
[root@pc1 test01]# python3 test.py      ## 运行结果
[2, 4, 10]

 

004、函数结构实现

[root@pc1 test01]# ls
test.py
[root@pc1 test01]# cat test.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

str1 = "GATATATGCATATACTT"
str2 = "ATAT"

def get_idx(x,y):         ## 定义函数
        list1 = []
        idx = x.find(y)
        while idx != -1:
                list1.append(idx + 1)
                idx = x.find(y, idx + 1)
        return list1
print(get_idx(str1, str2))
[root@pc1 test01]# python3 test.py     ## 计算结果
[2, 4, 10]

 。

参考:https://mp.weixin.qq.com/s?__biz=MzIxMjQxMDYxNA==&mid=2247484218&idx=1&sn=4ffe37427e4bb7de12b9db984d67a7d1&chksm=9747caa3a03043b5886f4eca3d3d56b4cbb7be20b361de08eeeb5f1b64bbef726d473409b52e&cur_album_id=1635727573621997580&scene=190#rd 

 

posted @ 2023-08-30 21:27  小鲨鱼2018  阅读(22)  评论(0编辑  收藏  举报