我有一个字符串。我想通过更改字符串中的字符顺序来生成该字符串的所有排列。例如,说:
x='stack'
我想要的是这样的清单,
l=['stack','satck','sackt'.......]
目前,我正在迭代字符串的列表强制转换,随机选择2个字母并将它们换位以形成新的字符串,然后将其添加到设置的l强制转换中。根据字符串的长度,我正在计算可能的排列数量,并继续迭代直到集合大小达到极限。必须有更好的方法来做到这一点。
我有一个字符串。我想通过更改字符串中的字符顺序来生成该字符串的所有排列。例如,说:
x='stack'
我想要的是这样的清单,
l=['stack','satck','sackt'.......]
目前,我正在迭代字符串的列表强制转换,随机选择2个字母并将它们换位以形成新的字符串,然后将其添加到设置的l强制转换中。根据字符串的长度,我正在计算可能的排列数量,并继续迭代直到集合大小达到极限。必须有更好的方法来做到这一点。
Answers:
itertools模块具有一个有用的方法,称为permutations()。该文件说:
itertools.permutations(iterable [,r])
返回迭代器中元素的连续r长度排列。
如果未指定r或为None,则r默认为可迭代的长度,并生成所有可能的全长置换。
排列以字典顺序排序。因此,如果对输入的iterable进行排序,则将按排序顺序生成置换元组。
不过,您必须将排列的字母作为字符串连接起来。
>>> from itertools import permutations
>>> perms = [''.join(p) for p in permutations('stack')]
>>> perms
[“堆栈”,“ stakc”,“ stcak”,“ stcka”,“ stkac”,“ stkca”,“ satck”,“ satkc”,“ sactk”,“ sackt”,“ saktc”,“ sakct”,“ sctak”,“ sctka”,“ scatk”,“ scakt”,“ sckta”,“ sckat”,“ sktac”,“ sktca”,“ skatc”,“ skact”,“ skcta”,“ skcat”,“ tsack” ,“ tsakc”,“ tscak”,“ tscka”,“ tskac”,“ tskca”,“ tasck”,“ taskc”,“ tacsk”,“ tacks”,“ taksc”,“ takcs”,“ tcsak”,“ tcska”,“ tcask”,“ tcaks”,“ tcksa”,“ tckas”,“ tksac”,“ tksca”,“ tkasc”,“ tkacs”,“ tkcsa”,“ tkcas”,“ astck”,“astkc”,“ asctk”,“ asckt”,“ asktc”,“ askct”,“ atsck”,“ atskc”,“ atcsk”,“ atcks”,“ atksc”,“ atkcs”,“ acstk”,“ acskt” ,“ actsk”,“ actks”,“ ackst”,“ ackts”,“ akstc”,“ aksct”,“ aktsc”,“ aktcs”,“ akcst”,“ akcts”,“ cstak”,“ cstka”,“ csatk”,“ csakt”,“ cskta”,“ cskat”,“ ctsak”,“ ctska”,“ ctask”,“ ctaks”,“ ctksa”,“ ctkas”,“ castk”,“ caskt”,“ catsk” ,“ catks”,“ cakst”,“ cakts”,“ cksta”,“ cksat”,“ cktsa”,“ cktas”,“ ckast”,“ ckats”,“ kstac”,“ kstca”,“ ksatc”,'ksact','kscta','kscat','ktsac','ktsca','ktasc','ktacs','ktcsa','ktcas','kastc','kasct','katsc','katcs ','kacst','kacts','kcsta','kcsat','kctsa','kctas','kcast','kcats']
如果您发现自己受到重复的困扰,请尝试将数据拟合到没有重复的结构中,例如set
:
>>> perms = [''.join(p) for p in permutations('stacks')]
>>> len(perms)
720
>>> len(set(perms))
360
感谢@pst指出这不是我们传统上认为的类型转换,而是更多的对set()
构造函数的调用。
你可以得到全部N!没有太多代码的排列
def permutations(string, step = 0):
# if we've gotten to the end, print the permutation
if step == len(string):
print "".join(string)
# everything to the right of step has not been swapped yet
for i in range(step, len(string)):
# copy the string (store as array)
string_copy = [character for character in string]
# swap the current index with the step
string_copy[step], string_copy[i] = string_copy[i], string_copy[step]
# recurse on the portion of the string that has not been swapped yet (now it's index will begin with step + 1)
permutations(string_copy, step + 1)
step == len(string)
代替step == len(string) - 1
?
这是用最少的代码完成字符串置换的另一种方法。我们基本上创建了一个循环,然后每次都交换两个字符,在循环内我们将进行递归操作。注意,我们仅在索引器达到字符串长度时才打印。示例:ABC i是我们的起点,而递归参数j是我们的循环
这是一个视觉上的帮助,它如何从左到右从上到下(排列顺序)
编码 :
def permute(data, i, length):
if i==length:
print(''.join(data) )
else:
for j in range(i,length):
#swap
data[i], data[j] = data[j], data[i]
permute(data, i+1, length)
data[i], data[j] = data[j], data[i]
string = "ABC"
n = len(string)
data = list(string)
permute(data, 0, n)
Stack Overflow用户已经发布了一些强大的解决方案,但是我想展示另一个解决方案。我觉得这更直观
这个想法是对于给定的字符串:我们可以通过算法(伪代码)进行递归:
permutations = char + permutations(string-char)表示字符串中的char
希望对您有所帮助!
def permutations(string):
"""
Create all permutations of a string with non-repeating characters
"""
permutation_list = []
if len(string) == 1:
return [string]
else:
for char in string:
[permutation_list.append(char + a) for a in permutations(string.replace(char, "", 1))]
return permutation_list
这是一个返回唯一排列的简单函数:
def permutations(string):
if len(string) == 1:
return string
recursive_perms = []
for c in string:
for perm in permutations(string.replace(c,'',1)):
revursive_perms.append(c+perm)
return set(revursive_perms)
revursive_perms
-> recursive_perms
。2.如果recursive_perms
是集合,而不是在return语句中转换为集合的列表,它将节省RAM和时间。3.使用字符串切片而不是.replace
构造arg的递归调用会更有效permutations
。4.string
用作变量名不是一个好主意,因为它遮盖了标准string
模块的名称。
这是不同于@Adriano和@illerucis发布的另一种方法。这具有更好的运行时,您可以通过测量时间来检查自己:
def removeCharFromStr(str, index):
endIndex = index if index == len(str) else index + 1
return str[:index] + str[endIndex:]
# 'ab' -> a + 'b', b + 'a'
# 'abc' -> a + bc, b + ac, c + ab
# a + cb, b + ca, c + ba
def perm(str):
if len(str) <= 1:
return {str}
permSet = set()
for i, c in enumerate(str):
newStr = removeCharFromStr(str, i)
retSet = perm(newStr)
for elem in retSet:
permSet.add(c + elem)
return permSet
对于任意字符串“ dadffddxcf”,排列库花费了1.1336秒,此实现花费了9.125秒,@ Adriano和@illerucis版本花费了16.357秒。当然,您仍然可以对其进行优化。
itertools.permutations
很好,但是对于包含重复元素的序列并不能很好地处理。这是因为在内部它会置换序列索引,而忽略序列项的值。
当然,可以过滤掉itertools.permutations
一个集合的输出以消除重复项,但是仍然浪费时间生成那些重复项,并且如果基本序列中有多个重复元素,那么将会有很多重复项。同样,使用集合保存结果会浪费RAM,首先就没有使用迭代器的好处。
幸运的是,有更有效的方法。下面的代码使用了14世纪印度数学家Narayana Pandita的算法,该算法可以在Wikipedia上有关置换的文章中找到。这种古老的算法仍然是已知的按顺序生成置换的最快方法之一,并且它非常健壮,因为它可以正确处理包含重复元素的置换。
def lexico_permute_string(s):
''' Generate all permutations in lexicographic order of string `s`
This algorithm, due to Narayana Pandita, is from
https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
To produce the next permutation in lexicographic order of sequence `a`
1. Find the largest index j such that a[j] < a[j + 1]. If no such index exists,
the permutation is the last permutation.
2. Find the largest index k greater than j such that a[j] < a[k].
3. Swap the value of a[j] with that of a[k].
4. Reverse the sequence from a[j + 1] up to and including the final element a[n].
'''
a = sorted(s)
n = len(a) - 1
while True:
yield ''.join(a)
#1. Find the largest index j such that a[j] < a[j + 1]
for j in range(n-1, -1, -1):
if a[j] < a[j + 1]:
break
else:
return
#2. Find the largest index k greater than j such that a[j] < a[k]
v = a[j]
for k in range(n, j, -1):
if v < a[k]:
break
#3. Swap the value of a[j] with that of a[k].
a[j], a[k] = a[k], a[j]
#4. Reverse the tail of the sequence
a[j+1:] = a[j+1:][::-1]
for s in lexico_permute_string('data'):
print(s)
输出
aadt
aatd
adat
adta
atad
atda
daat
data
dtaa
taad
tada
tdaa
当然,如果要将收集的字符串收集到列表中,则可以执行
list(lexico_permute_string('data'))
或最新的Python版本中:
[*lexico_permute_string('data')]
你为什么不简单做:
from itertools import permutations
perms = [''.join(p) for p in permutations(['s','t','a','c','k'])]
print perms
print len(perms)
print len(set(perms))
您不会看到重复的内容:
['stack', 'stakc', 'stcak', 'stcka', 'stkac', 'stkca', 'satck', 'satkc',
'sactk', 'sackt', 'saktc', 'sakct', 'sctak', 'sctka', 'scatk', 'scakt', 'sckta',
'sckat', 'sktac', 'sktca', 'skatc', 'skact', 'skcta', 'skcat', 'tsack',
'tsakc', 'tscak', 'tscka', 'tskac', 'tskca', 'tasck', 'taskc', 'tacsk', 'tacks',
'taksc', 'takcs', 'tcsak', 'tcska', 'tcask', 'tcaks', 'tcksa', 'tckas', 'tksac',
'tksca', 'tkasc', 'tkacs', 'tkcsa', 'tkcas', 'astck', 'astkc', 'asctk', 'asckt',
'asktc', 'askct', 'atsck', 'atskc', 'atcsk', 'atcks', 'atksc', 'atkcs', 'acstk',
'acskt', 'actsk', 'actks', 'ackst', 'ackts', 'akstc', 'aksct', 'aktsc', 'aktcs',
'akcst', 'akcts', 'cstak', 'cstka', 'csatk', 'csakt', 'cskta', 'cskat', 'ctsak',
'ctska', 'ctask', 'ctaks', 'ctksa', 'ctkas', 'castk', 'caskt', 'catsk', 'catks',
'cakst', 'cakts', 'cksta', 'cksat', 'cktsa', 'cktas', 'ckast', 'ckats', 'kstac',
'kstca', 'ksatc', 'ksact', 'kscta', 'kscat', 'ktsac', 'ktsca', 'ktasc', 'ktacs',
'ktcsa', 'ktcas', 'kastc', 'kasct', 'katsc', 'katcs', 'kacst', 'kacts', 'kcsta',
'kcsat', 'kctsa', 'kctas', 'kcast', 'kcats']
120
120
[Finished in 0.3s]
def permute(seq):
if not seq:
yield seq
else:
for i in range(len(seq)):
rest = seq[:i]+seq[i+1:]
for x in permute(rest):
yield seq[i:i+1]+x
print(list(permute('stack')))
这是illerucis代码的稍微改进的版本,用于s
在不使用itertools的情况下返回具有不同字符的字符串的所有排列列表(不一定按字典顺序):
def get_perms(s, i=0):
"""
Returns a list of all (len(s) - i)! permutations t of s where t[:i] = s[:i].
"""
# To avoid memory allocations for intermediate strings, use a list of chars.
if isinstance(s, str):
s = list(s)
# Base Case: 0! = 1! = 1.
# Store the only permutation as an immutable string, not a mutable list.
if i >= len(s) - 1:
return ["".join(s)]
# Inductive Step: (len(s) - i)! = (len(s) - i) * (len(s) - i - 1)!
# Swap in each suffix character to be at the beginning of the suffix.
perms = get_perms(s, i + 1)
for j in range(i + 1, len(s)):
s[i], s[j] = s[j], s[i]
perms.extend(get_perms(s, i + 1))
s[i], s[j] = s[j], s[i]
return perms
另一个主动和递归的解决方案。这个想法是选择一个字母作为枢轴,然后创建一个单词。
# for a string with length n, there is a factorial n! permutations
alphabet = 'abc'
starting_perm = ''
# with recursion
def premuate(perm, alphabet):
if not alphabet: # we created one word by using all letters in the alphabet
print(perm + alphabet)
else:
for i in range(len(alphabet)): # iterate over all letters in the alphabet
premuate(perm + alphabet[i], alphabet[0:i] + alphabet[i+1:]) # chose one letter from the alphabet
# call it
premuate(starting_perm, alphabet)
输出:
abc
acb
bac
bca
cab
cba
def f(s):
if len(s) == 2:
X = [s, (s[1] + s[0])]
return X
else:
list1 = []
for i in range(0, len(s)):
Y = f(s[0:i] + s[i+1: len(s)])
for j in Y:
list1.append(s[i] + j)
return list1
s = raw_input()
z = f(s)
print z
from itertools import permutations
perms = [''.join(p) for p in permutations('ABC')]
perms = [''.join(p) for p in permutations('stack')]
该程序不会消除重复项,但我认为它是最有效的方法之一:
s=raw_input("Enter a string: ")
print "Permutations :\n",s
size=len(s)
lis=list(range(0,size))
while(True):
k=-1
while(k>-size and lis[k-1]>lis[k]):
k-=1
if k>-size:
p=sorted(lis[k-1:])
e=p[p.index(lis[k-1])+1]
lis.insert(k-1,'A')
lis.remove(e)
lis[lis.index('A')]=e
lis[k:]=sorted(lis[k:])
list2=[]
for k in lis:
list2.append(s[k])
print "".join(list2)
else:
break
def permute_all_chars(list, begin, end):
if (begin == end):
print(list)
return
for current_position in range(begin, end + 1):
list[begin], list[current_position] = list[current_position], list[begin]
permute_all_chars(list, begin + 1, end)
list[begin], list[current_position] = list[current_position], list[begin]
given_str = 'ABC'
list = []
for char in given_str:
list.append(char)
permute_all_chars(list, 0, len(list) -1)
所有可能的单词都带有堆栈
from itertools import permutations
for i in permutations('stack'):
print(''.join(i))
permutations(iterable, r=None)
返回迭代器中元素的连续r长度排列。
如果未指定r或为None,则r默认为可迭代的长度,并生成所有可能的全长排列。
排列以字典顺序排序。因此,如果对输入的iterable进行排序,则将按排序顺序生成置换元组。
元素根据其位置而不是其价值被视为唯一。因此,如果输入元素是唯一的,则每个排列中将没有重复值。
这是一种递归解决方案,使用n!
该解决方案可以接受字符串中的重复元素
import math
def getFactors(root,num):
sol = []
# return condition
if len(num) == 1:
return [root+num]
# looping in next iteration
for i in range(len(num)):
# Creating a substring with all remaining char but the taken in this iteration
if i > 0:
rem = num[:i]+num[i+1:]
else:
rem = num[i+1:]
# Concatenating existing solutions with the solution of this iteration
sol = sol + getFactors(root + num[i], rem)
return sol
我考虑了两个要素(组合的数量为n!
,结果不能包含重复项)验证了解决方案。所以:
inpt = "1234"
results = getFactors("",inpt)
if len(results) == math.factorial(len(inpt)) | len(results) != len(set(results)):
print("Wrong approach")
else:
print("Correct Approach")
这是一个简单直接的递归实现;
def stringPermutations(s):
if len(s) < 2:
yield s
return
for pos in range(0, len(s)):
char = s[pos]
permForRemaining = list(stringPermutations(s[0:pos] + s[pos+1:]))
for perm in permForRemaining:
yield char + perm
stringPermutations
列表中-您可以直接在其上进行迭代,例如for perm in stringPermutations(s[:pos] + s[pos+1:]):
。另外,您可以for
使用enumerate
代替来简化循环range
,并消除char = s[pos]
赋值:for pos, char in enumerate(s):
。
递归
# swap ith and jth character of string
def swap(s, i, j):
q = list(s)
q[i], q[j] = q[j], q[i]
return ''.join(q)
# recursive function
def _permute(p, s, permutes):
if p >= len(s) - 1:
permutes.append(s)
return
for i in range(p, len(s)):
_permute(p + 1, swap(s, p, i), permutes)
# helper function
def permute(s):
permutes = []
_permute(0, s, permutes)
return permutes
# TEST IT
s = "1234"
all_permute = permute(s)
print(all_permute)
使用迭代方法(使用堆栈)
# swap ith and jth character of string
def swap(s, i, j):
q = list(s)
q[i], q[j] = q[j], q[i]
return ''.join(q)
# iterative function
def permute_using_stack(s):
stk = [(0, s)]
permutes = []
while len(stk) > 0:
p, s = stk.pop(0)
if p >= len(s) - 1:
permutes.append(s)
continue
for i in range(p, len(s)):
stk.append((p + 1, swap(s, p, i)))
return permutes
# TEST IT
s = "1234"
all_permute = permute_using_stack(s)
print(all_permute)
按词典顺序排序
# swap ith and jth character of string
def swap(s, i, j):
q = list(s)
q[i], q[j] = q[j], q[i]
return ''.join(q)
# finds next lexicographic string if exist otherwise returns -1
def next_lexicographical(s):
for i in range(len(s) - 2, -1, -1):
if s[i] < s[i + 1]:
m = s[i + 1]
swap_pos = i + 1
for j in range(i + 1, len(s)):
if m > s[j] > s[i]:
m = s[j]
swap_pos = j
if swap_pos != -1:
s = swap(s, i, swap_pos)
s = s[:i + 1] + ''.join(sorted(s[i + 1:]))
return s
return -1
# helper function
def permute_lexicographically(s):
s = ''.join(sorted(s))
permutes = []
while True:
permutes.append(s)
s = next_lexicographical(s)
if s == -1:
break
return permutes
# TEST IT
s = "1234"
all_permute = permute_lexicographically(s)
print(all_permute)
set(...)
不“投射”。相反,它生成(并产生)表示输入集合的集合:生成后,它与输入集合没有关联(并且是一个不同的对象,而不仅仅是一个不同的视图)。