【问题标题】:Match characters of a string in another string in the same order in Python在Python中以相同的顺序匹配另一个字符串中的一个字符串的字符
【发布时间】:2019-05-20 07:54:52
【问题描述】:

这是一个基本问题,但我在任何地方都找不到正确的答案。 我在python中有2个相等长度的字符串,我想知道第二个字符串中是否至少包含第一个字符串的n个字符(n可以是小于字符串长度的任何数字)(以相同的顺序)。

例如:

s1 = 'TAGCACTTT'
s2 = 'CGATGATTT'
s3 = 'AGACGGCCT'
n = 6

匹配 s1 和 s2 应该返回 True,因为 s2 按顺序包含字母“AGATTT”,而匹配 s1 和 s3 应该返回 False,因为只有 5 个字母匹配。 我怎样才能有效地做到这一点?

【问题讨论】:

  • 在您的示例中n 是什么? 6?另外请添加您对此问题的尝试

标签: python python-3.x string-matching


【解决方案1】:
def max_sub(X, Y, m, n):
    if m == 0 or n == 0:
        return 0;
    elif X[m - 1] == Y[n - 1]:
        return 1 + max_sub(X, Y, m - 1, n - 1);
    else:
        return max(max_sub(X, Y, m, n - 1), max_sub(X, Y, m - 1, n))

s1 = 'TAGCACTTT'
s2 = 'CGATGATTT'
s3 = 'AGACGGCCT'
n = 6

# Permutations using library function
from itertools import permutations

# Get all permutations of [s1,s2,s3]
perm = permutations([s1, s2, s3],2)

# pass over the obtained permutations
for i in list(perm):
    len_ = max_sub(i[0], i[1], len(i[0]), len(i[1]))
    if len_ >= n:
        print("For {},{} length of common substring is: {}, True ".format(i[0], i[1], max_sub(i[0], i[1], len(i[0]), len(i[1]))))
    else:
        print("For {},{} length of common substring is: {}, False ".format(i[0], i[1], max_sub(i[0], i[1], len(i[0]), len(i[1]))))

输出:

For TAGCACTTT,CGATGATTT length of common substring is: 6, True 
For TAGCACTTT,AGACGGCCT length of common substring is: 5, False 
For CGATGATTT,TAGCACTTT length of common substring is: 6, True 
For CGATGATTT,AGACGGCCT length of common substring is: 4, False 
For AGACGGCCT,TAGCACTTT length of common substring is: 5, False 
For AGACGGCCT,CGATGATTT length of common substring is: 4, False 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多