Python – N 大小的子字符串,具有 K 个不同的字符
给定一个字符串,任务是编写一个Python程序来提取大小为 N 且具有 K 个不同字符的字符串。
例子:
Input : test_str = ‘geeksforgeeksforgeeks’, N = 3, K = 2
Output : [‘gee’, ‘eek’, ‘gee’, ‘eek’, ‘gee’, ‘eek’]
Explanation : 3 lengths have 2 unique characters are extracted.
Input : test_str = ‘geeksforgeeksforgeeks’, N = 4, K = 2
Output : []
Explanation : No strings with 4 length and just have 2 elements.
方法 #1:使用切片+ set() + 循环
在此我们执行使用切片获取 N 个块的任务,set() 用于检查唯一元素。循环用于迭代所有可能的块。
Python3
# Python3 code to demonstrate working of
# N sized substrings with K distinct characters
# Using slicing + set() + loop
# initializing string
test_str = 'geeksforgeeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing N
N = 3
# initializing K
K = 2
res = []
for idx in range(0, len(test_str) - N + 1):
# getting unique elements off sliced string
if (len(set(test_str[idx: idx + N])) == K):
res.append(test_str[idx: idx + N])
# printing result
print("Extracted Strings : " + str(res))
Python3
# Python3 code to demonstrate working of
# N sized substrings with K distinct characters
# Using list comprehension + len() + set() + slicing
# initializing string
test_str = 'geeksforgeeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing N
N = 3
# initializing K
K = 2
# list comprehension used to slice
res = [test_str[idx: idx + N]
for idx in range(0, len(test_str) - N + 1)
if len(set(test_str[idx: idx + N])) == K]
# printing result
print("Extracted Strings : " + str(res))
输出
The original string is : geeksforgeeksforgeeks
Extracted Strings : ['gee', 'eek', 'gee', 'eek', 'gee', 'eek']
方法 #2:使用列表推导+ len() + set() +切片
与上述方法类似,唯一的区别是使用列表理解而不是循环,只是为了提供解决此任务的速记。
蟒蛇3
# Python3 code to demonstrate working of
# N sized substrings with K distinct characters
# Using list comprehension + len() + set() + slicing
# initializing string
test_str = 'geeksforgeeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing N
N = 3
# initializing K
K = 2
# list comprehension used to slice
res = [test_str[idx: idx + N]
for idx in range(0, len(test_str) - N + 1)
if len(set(test_str[idx: idx + N])) == K]
# printing result
print("Extracted Strings : " + str(res))
输出
The original string is : geeksforgeeksforgeeks
Extracted Strings : ['gee', 'eek', 'gee', 'eek', 'gee', 'eek']