小白教程

 找回密码
 立即注册
查看: 5698|回复: 3

Python 求字符串集的所有子串

[复制链接]

1

主题

3

帖子

7

积分

新手上路

Rank: 1

积分
7
发表于 2021-3-20 12:24:23 | 显示全部楼层 |阅读模式
查找字符串集合的所有子字符串,如'ABC'子字符串'a ', 'B', 'C', 'ab', 'BC'和'ABC'。现在的想法是根据位控制长度遍历所有字符串,并在判断重复后将它们写入列表。但是,如果字符串长度太长,次数太多,那么循环的次数就会太多,程序就不会运行。我希望你能给一些建议。谢谢你!

回复

使用道具 举报

4

主题

5

帖子

14

积分

新手上路

Rank: 1

积分
14
发表于 2021-3-30 00:22:05 | 显示全部楼层
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Python 3.6
  4. from itertools import accumulate

  5. def all_sub_string(a_string):
  6.     if len(a_string) == 1:
  7.         return [a_string]
  8.     else:
  9.         return list(accumulate(a_string)) + all_sub_string(a_string[1:])


  10. print(all_sub_string('abcde'))
复制代码
回复

使用道具 举报

1

主题

2

帖子

5

积分

新手上路

Rank: 1

积分
5
发表于 2021-4-1 17:51:19 | 显示全部楼层
是遍历长度,然后可以组合,有函数可用
回复

使用道具 举报

1

主题

5

帖子

11

积分

新手上路

Rank: 1

积分
11
发表于 2021-4-19 05:15:20 | 显示全部楼层
  1. def subsets(nums):
  2.         res = []
  3.         def backtrack(nums, tmp):
  4.             res.append(tmp)
  5.             for i in range(len(nums)):
  6.                 backtrack(nums[i+1:], tmp+[nums[i]])
  7.         backtrack(nums, [])
  8.         return res
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 14:48 , Processed in 0.037334 second(s), 27 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

快速回复 返回顶部 返回列表