Python中字符串的所有排列(递归) [英] All Permutations of a String in Python (Recursive)

查看:843
本文介绍了Python中字符串的所有排列(递归)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在这头上踢一下.我定义了以下递归函数:

I need a kick in the head on this one. I have the following recursive function defined:

def perms(s):
  if(len(s)==1):
    return s

  res = ''
  for x in xrange(len(s)):

    res += s[x] + perms(s[0:x] + s[x+1:len(s)])

  return res + '\n'

perms("abc")当前返回:

perms("abc") currently returns:

abccb
bacca
cabba

所需的结果是

abc
acd
bac
bca
cab
cba

我在哪里错了?我如何对此有所不同才能提出解决方案?

注意:我知道itertools函数.我正在尝试了解如何为自己的学习递归地实现排列.这就是为什么我希望有人指出我的代码出了什么问题以及如何以不同的思维方式解决它.谢谢!

Note: I am aware of the itertools function. I am trying to understand how to implement permutations recursively for my own learning. That is why I would prefer someone to point out what is wrong with my code, and how to think differently to solve it. Thanks!

推荐答案

你去了(递归排列):

def Permute(string):
    if len(string) == 0:
        return ['']
    prevList = Permute(string[1:len(string)])
    nextList = []
    for i in range(0,len(prevList)):
        for j in range(0,len(string)):
            newString = prevList[i][0:j]+string[0]+prevList[i][j:len(string)-1]
            if newString not in nextList:
                nextList.append(newString)
    return nextList

为了获得所有排列字符串的列表,只需使用输入字符串调用上面的函数即可.例如,

In order to get a list of all permutation strings, simply call the function above with your input string. For example,

stringList = Permute('abc')

为了获得由所有换行符分隔的单个字符串,用换行符分隔,只需使用该函数的输出调用'\n'.join即可.例如,

In order to get a single string of all permutation strings separated by new-line characters, simply call '\n'.join with the output of that function. For example,

string = '\n'.join(Permute('abc'))

顺便说一句,上面两个选项的print结果是相同的.

By the way, the print results for the two options above are identical.

这篇关于Python中字符串的所有排列(递归)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆