Python 求字符串集的所有子串

lzw2016 2017-10-30 08:27:08
求字符串集的所有子串,如‘abc’子串‘a’、‘b’、‘c’、‘ab’、‘bc’、‘abc’。现在有思路是对所有字符串按位控制长度进行遍历,判重后再写入列表中。但是如果字符串长度过长,数目过多,循环次数就很多,程序运行不了。希望各位大能门给点建议,谢谢
...全文
1464 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
向天抡大锤 2021-02-27
  • 打赏
  • 举报
回复
回溯法,不要求子串顺序的话需要考虑 有没有重复元素

def subsets(nums):
        res = []
        def backtrack(nums, tmp):
            res.append(tmp)
            for i in range(len(nums)):
                backtrack(nums[i+1:], tmp+[nums[i]])
        backtrack(nums, [])
        return res
weixin_45903952 2020-04-04
  • 打赏
  • 举报
回复 1
import itertools
str1="ABC"
for num in range(1,len(str1)+1):
    for i in itertools.combinations(str1, num):
        print (''.join(i))
print()
A B C AB AC BC ABC
weixin_45903952 2020-04-04
  • 打赏
  • 举报
回复
str1="ABC" for num in range(1,len(str1)+1): import itertools for i in itertools.combinations(str1, num): print (''.join(i)) print()
weixin_45903952 2020-04-04
  • 打赏
  • 举报
回复
就是遍历长度,然后组合就可以了,有现成的函数可用
Theyearling 2020-04-03
  • 打赏
  • 举报
回复
混沌鳄鱼 2017-10-31
  • 打赏
  • 举报
回复
引用 4 楼 pythonner_ljx 的回复:
博主你好,我刚开始学python,学python有前途么
没有,去学java或C++吧,等学精通了,回来看30分钟python教程你就会了。
lu_jianxin 2017-10-31
  • 打赏
  • 举报
回复
博主你好,我刚开始学python,学python有前途么
混沌鳄鱼 2017-10-31
  • 打赏
  • 举报
回复
引用 2 楼 xpresslink 的回复:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python 3.6
from itertools import accumulate

def all_sub_string(a_string):
    if len(a_string) == 1:
        return [a_string]
    else:
        return list(accumulate(a_string)) + all_sub_string(a_string[1:])


print(all_sub_string('abcde'))

结果的样子: ['a', 'ab', 'abc', 'abcd', 'abcde', 'b', 'bc', 'bcd', 'bcde', 'c', 'cd', 'cde', 'd', 'de', 'e']
混沌鳄鱼 2017-10-31
  • 打赏
  • 举报
回复

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python 3.6
from itertools import accumulate

def all_sub_string(a_string):
    if len(a_string) == 1:
        return [a_string]
    else:
        return list(accumulate(a_string)) + all_sub_string(a_string[1:])


print(all_sub_string('abcde'))

lzw2016 2017-10-30
  • 打赏
  • 举报
回复 1
有没有人啊

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧