Python - 查找字符串重叠子串的所有组合
给定一个字符串,任务是编写一个Python程序来查找一个字符串的重叠子串的所有组合并将其存储在一个列表中。列表列表将按子字符串的长度进行排序和分组。
Input : test_str = ‘Geeks4G’
Output : [[”, ”, ”, ”, ”, ”, ”, ”], [‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘4’, ‘G’], [‘Ge’, ‘ee’, ‘ek’, ‘ks’, ‘s4’, ‘4G’], [‘Gee’, ‘eek’, ‘eks’, ‘ks4’, ‘s4G’], [‘Geek’, ‘eeks’, ‘eks4’, ‘ks4G’], [‘Geeks’, ‘eeks4’, ‘eks4G’], [‘Geeks4’, ‘eeks4G’], [‘Geeks4G’]]
Explanation : All lengths overlapping substrings extracted.
Input : test_str = ‘Geeks’
Output : [[”, ”, ”, ”, ”, ”], [‘G’, ‘e’, ‘e’, ‘k’, ‘s’], [‘Ge’, ‘ee’, ‘ek’, ‘ks’], [‘Gee’, ‘eek’, ‘eks’], [‘Geek’, ‘eeks’], [‘Geeks’]]
Explanation : All lengths overlapping substrings extracted.
方法:使用列表理解、切片和循环
在这里,我们执行使用切片获取每个切片的任务,使用列表理解创建所有特定大小的字符串。所有尺寸的操作都是使用循环完成的。后来所有都打印为列表列表。
例子:
Python3
# Python3 code to demonstrate working of
# Overlapping substrings of all lengths
# Using list comprehension + slicing + loop
# initializing string
test_str = 'Geeks4G'
# printing original string
print("The original string is : " + str(test_str))
# manipulating overlap size using loop
res = []
for idx in range(len(test_str) + 1):
# getting overlap strings
res.append([test_str[j: j + idx] for j in range(len(test_str) - idx + 1)])
# printing result
print("All overlapping Strings : " + str(res))
输出:
The original string is : Geeks4G
All overlapping Strings : [[”, ”, ”, ”, ”, ”, ”, ”], [‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘4’, ‘G’], [‘Ge’, ‘ee’, ‘ek’, ‘ks’, ‘s4’, ‘4G’], [‘Gee’, ‘eek’, ‘eks’, ‘ks4’, ‘s4G’], [‘Geek’, ‘eeks’, ‘eks4’, ‘ks4G’], [‘Geeks’, ‘eeks4’, ‘eks4G’], [‘Geeks4’, ‘eeks4G’], [‘Geeks4G’]]