📜  Python – 长度为 K 的子字符串匹配的位置数

📅  最后修改于: 2022-05-13 01:54:39.652000             🧑  作者: Mango

Python – 长度为 K 的子字符串匹配的位置数

给定 2 个字符串,计算长度为 K 的子字符串匹配的位置。

方法 #1:使用列表理解 + min() + 切片

在此,我们遍历字符串直到最小字符串的长度,并通过使用字符串切片进行切片来完成比较。迭代是通过列表理解中的循环完成的。

Python3
# Python3 code to demonstrate working of 
# Number of positions where Substrings Match of Length K
# Using list comprehension + min() + slicing
  
# initializing strings
test_str1 = 'geeksforgeeks'
test_str2 = 'peeksformeeks'
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# initializing K 
K = 3 
  
# checking for substrings, 
# using len() to get total count
res = len([test_str1[idx : idx + K] for idx in range(min(len(test_str1), len(test_str2)) - K - 1)
        if test_str1[idx : idx + K] == test_str2[idx : idx + K]])
  
# printing result 
print("Number of positions of matching K length Substrings : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Number of positions where Substrings Match of Length K
# Using map() + list comprehension
  
# initializing strings
test_str1 = 'geeksforgeeks'
test_str2 = 'peeksformeeks'
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# initializing K 
K = 3 
  
# Extracting Substrings
subs_str = [test_str1[idx : idx + K] for idx in range(len(test_str1) - K - 1)]
  
# checking in other string
# using count() to get number
res = list(map(lambda ele: ele in test_str2, subs_str)).count(True)
  
# printing result 
print("Number of positions of matching K length Substrings : " + str(res))


输出
The original string 1 is : geeksforgeeks
The original string 2 is : peeksformeeks
Number of positions of matching K length Substrings : 5

方法 #2:使用 map() + 列表推导

在此,我们提取一个字符串的所有 K 长度子字符串,然后使用 in运算符和映射,检查每个子字符串是否存在于其他字符串中,这忽略了问题的位置因素。

Python3

# Python3 code to demonstrate working of 
# Number of positions where Substrings Match of Length K
# Using map() + list comprehension
  
# initializing strings
test_str1 = 'geeksforgeeks'
test_str2 = 'peeksformeeks'
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# initializing K 
K = 3 
  
# Extracting Substrings
subs_str = [test_str1[idx : idx + K] for idx in range(len(test_str1) - K - 1)]
  
# checking in other string
# using count() to get number
res = list(map(lambda ele: ele in test_str2, subs_str)).count(True)
  
# printing result 
print("Number of positions of matching K length Substrings : " + str(res)) 
输出
The original string 1 is : geeksforgeeks
The original string 2 is : peeksformeeks
Number of positions of matching K length Substrings : 5