【问题标题】:How to get all substrings & all character permutations of all substings? [duplicate]如何获取所有子字符串的所有子字符串和所有字符排列? [复制]
【发布时间】:2020-09-19 19:49:41
【问题描述】:

我有一个字符串 f.e. str = 'abc'

我想得到这样的所有组合:

'a', 'b', 'c', 'ab', 'ac', 'ba', 'bc', 'ca','cb', 'abc', 'acb', 'bca' , 'bac', 'cab', 'cba'

我试过了

def string_set(str):
    n = len(str) 
    arr = [] 

    for i in range(0,n):  
        for j in range(i,n): 
            arr.append(str[i:(j+1)])

    return arr

但它给了我:

'a', 'ab', 'abc', 'b', 'bc', 'c'. 

我怎样才能包括其余的?

【问题讨论】:

  • 因为你在做str[i:(j+1)] 你只得到“连续”的子串。此外,str 是一个非常糟糕的变量名选择
  • @DeepSpace 子字符串根据定义是连续的。他们想要的不仅仅是子字符串。
  • 应该回答这个问题的问题没有回答它。它不处理排列,这里的 OP 也需要所有排列。
  • @zabop 不过差不多。只需将组合更改为排列即可。
  • 是的,但几乎重复不是重复。

标签: python string set


【解决方案1】:
import itertools

你可以这样做,使用 itertools permutations & combinations:

def string_set(x):
    arr = [''.join(l) for i in range(len(x)) for l in itertools.combinations(x, i+1)]     
    reslist=[]   
    for eachpermut in arr:
        for each in [''.join(eachpermut) for eachpermut in list(itertools.permutations(eachpermut))]:
            reslist.append(each)
    return reslist

如果您喜欢一行中的所有内容:

def string_set(x):
    return [each for eachpermut in [''.join(l) for i in range(len(x)) for l in itertools.combinations(x, i+1)] for each in [''.join(eachpermut) for eachpermut in list(itertools.permutations(eachpermut))]]

string_set('abc') 返回:

['a',
 'b',
 'c',
 'ab',
 'ba',
 'ac',
 'ca',
 'bc',
 'cb',
 'abc',
 'acb',
 'bac',
 'bca',
 'cab',
 'cba']

如果你不想导入itertools,你可以只使用他们的permutations函数:

def permutations(iterable, r=None):
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

然后只需在上面的代码中使用permutations 而不是itertools.permutations

combinations 也可以这样做。

【讨论】:

  • 我喜欢这个:) 顺便说一句。如果没有 itertools 库,我怎么能做到这一点?
  • 没有'ac', 'ca' ((
  • 哦,好的,正在调查...
  • @kishmish17 您的标题显示“所有子字符串及其所有排列”,这就是这段代码的作用(空子字符串除外)。 'ac' 和 'ca' 不是子串的排列。
  • 现在检查一下,我认为它有效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
  • 1970-01-01
  • 2019-12-08
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
相关资源
最近更新 更多