不使用itertools的所有字符串排列 [英] all permutations of string without using itertools
问题描述
可以由给定字符串形成的所有长度的所有可能字符串
All possible strings of any length that can be formed from a given string
输入:
abc
输出:
a b c abc ab ac bc bac bca
cb ca ba cab cba acb
我已经尝试过使用它,但仅限于字符串abc,我想将其概括化,就像输入"abcd"一样,我将为我提供相同的输出.
I have tried using this but it's limited to string abc, I want to generalize it like if input 'abcd' i will provide me output for the same.
def perm_main(elems):
perm=[]
for c in elems:
perm.append(c)
for i in range(len(elems)):
for j in range(len(elems)):
if perm[i]!= elems[j]:
perm.append(perm[i]+elems[j])
level=[elems[0]]
for i in range(1,len(elems)):
nList=[]
for item in level:
#print(item)
nList.append(item+elems[i])
#print(nList)
for j in range(len(item)):
#print(j)
nList.append(item[0:j]+ elems[i] + item[j:])
#print(nList)
level=nList
perm = perm + nList
return perm
推荐答案
You may not need itertools
, but you have the solution in the documentation, where itertools.permutations
is said to be roughly equivalent to:
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
或使用product
:
def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
for indices in product(range(n), repeat=r):
if len(set(indices)) == r:
yield tuple(pool[i] for i in indices)
它们都是生成器,因此您需要调用list(permutations(x))
来检索实际列表或将yields
替换为l.append(v)
,其中l
是定义为累加结果的列表,而v
是产生的值
They are both generators so you will need to call list(permutations(x))
to retrieve an actual list or substitute the yields
for l.append(v)
where l
is a list defined to accumulate results and v
is the yielded value.
对于所有可能的尺寸,请对其进行迭代:
For all the possible sizes ones, iterate over them:
from itertools import chain
check_string = "abcd"
all = list(chain.from_iterable(permutations(check_string , r=x)) for x in range(len(check_string )))
这篇关于不使用itertools的所有字符串排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!