首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python递归排列

Python递归排列
EN

Stack Overflow用户
提问于 2012-10-28 21:43:19
回答 10查看 64.9K关注 0票数 14

我在尝试使用递归编写置换代码时遇到了麻烦。这将返回一个列表,其中包含每个字母的所有可能位置。因此,对于单词cat,应该返回['cat','act',atc,'cta','tca','tac']。到目前为止,我有这个

代码语言:javascript
复制
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)

这里有一些步骤,但我不确定如何使用它们。

EN

Stack Overflow用户

发布于 2019-03-16 00:52:51

您可以使用一个函数在列表中迭代索引,并生成一个由索引处的值和其余列表值的排列组成的列表。下面是一个使用Python 3.5+特性的示例:

代码语言:javascript
复制
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'))返回:

代码语言:javascript
复制
[['a', 'b', 'c'],
 ['a', 'c', 'b'],
 ['b', 'a', 'c'],
 ['b', 'c', 'a'],
 ['c', 'a', 'b'],
 ['c', 'b', 'a']]
票数 5
EN
查看全部 10 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13109274

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档