找出一个字符串的所有可能的排列,但所有可能的长度



获得字符串的简单排列很容易,但是如果您想要不同长度的排列该如何做呢如:

def permutations(string):
if len(string) == 1:
return [string]
else:
perms = []
for i in range(len(string)):
for perm in permutations(string[:i] + string[i+1:]):
perms.append(string[i] + perm)
return perms
permutations('abc')

返回[' abc ',‘acb’,‘bac’,‘bca’,‘车’,‘cba)

但是我想[' abc ',‘acb’,‘bac’,‘bca’,"出租车","cba"、"ab"、"ba"、"公元前"、"cb"、"ca"、"交流"、",' b ', ' c ']

我怎么得到额外的安排????

你应该使用来自itertools的排列

from itertools import permutations
all_perm = []
st="abc"
for i in range(1,len(st)+1):
all_perm += list(permutations(st,i))

all_perms_str = [''.join(str(e) for e in perm) for perm in all_perm]
print (all_perms_str)

输出:

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

仅加一行:

def permutations(string):
if len(string) == 1:
return [string]
else:   # note: else not needed after return
perms = []
for i in range(len(string)):
for perm in permutations(string[:i] + string[i+1:]):
perms.append(string[i] + perm)
perms.append(string[i])  # <--- new line
return perms

输出:

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

相关内容

  • 没有找到相关文章

最新更新