[英]Generate all substrings of a given string
I want to generate all the possible substrings from a given string without redundant values as follows:我想从给定的字符串中生成所有可能的子字符串而没有冗余值,如下所示:
input: 'abba'
输入: 'abba'
output: 'a','b','ab','ba','abb','bba'
输出: 'a','b','ab','ba','abb','bba'
Here is my code这是我的代码
s='abba'
for i in range (0,len(s)):
for j in range (i+1,len(s)):
print(s[i:j])
My output is 'a','ab','abb','b','bb','b'
我的输出是'a','ab','abb','b','bb','b'
As you can see from the output 'b'
is repeated, and 'bba'
does not exist.正如您从输出中看到的那样, 'b'
是重复的,而'bba'
不存在。
I want to know and learn the right logic to produce all unique substrings.我想知道并学习生成所有唯一子字符串的正确逻辑。
Fixing the indexing a bit稍微修复索引
s='abba'
for i in range (0,len(s)):
for j in range (i,len(s)):
print(s[i:(j+1)])
yields the following output产生以下输出
a
ab
abb
abba
b
bb
bba
b
ba
a
Basically, the indexing fix takes into account that基本上,索引修复考虑到
'abba'[3:3]
produces just zero-length string ''
'abba'[3:3]
只产生零长度的字符串''
but但
'abba'[3:4]
produces string 'a'
which has length one. 'abba'[3:4]
产生长度为 1 的字符串'a'
。 Duplicates you may remove by using set()
, as follows:您可以使用set()
删除重复项,如下所示:
s='abba'
ss = set()
for i in range (0,len(s)):
for j in range (i,len(s)):
ss.add(s[i:(j+1)])
print(sorted(ss))
Then you will have the following result ['a', 'ab', 'abb', 'abba', 'b', 'ba', 'bb', 'bba']
.然后你会得到以下结果['a', 'ab', 'abb', 'abba', 'b', 'ba', 'bb', 'bba']
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.