我在尝试使用递归编写置换代码时遇到了麻烦。这将返回一个列表,其中包含每个字母的所有可能位置。因此,对于单词cat,应该返回['cat','act',atc,'cta','tca','tac']。到目前为止,我有这个
def permutations(s):
lst=[]
if len(s) == 1 or len(s) == 0 :
# Return a list containing the string, not the string
return [s]
# Call permutations to get the permutations that don't include the
# first character of s
plst = permutations(s[1:])
print(plst)
for item in plst:
print (item)
plst= permutations(s[1+1:])
# Now move through each possible position of the first character
# and create a new string that puts that character into the strings
# in plst
for i in range(len(s)):
pass
# Create a new string out of item
# and put it into lst
# Modify
for item in lst:
print(index)这里有一些步骤,但我不确定如何使用它们。
发布于 2019-03-16 00:52:51
您可以使用一个函数在列表中迭代索引,并生成一个由索引处的值和其余列表值的排列组成的列表。下面是一个使用Python 3.5+特性的示例:
def permutations(s):
if not s:
yield []
yield from ([s[i], *p] for i in range(len(s)) for p in permutations(s[:i] + s[i + 1:]))因此list(permutations('abc'))返回:
[['a', 'b', 'c'],
['a', 'c', 'b'],
['b', 'a', 'c'],
['b', 'c', 'a'],
['c', 'a', 'b'],
['c', 'b', 'a']]https://stackoverflow.com/questions/13109274
复制相似问题