python递归排序_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") currently returns:

abccb

bacca

cabba

The desired result is

abc

acd

bac

bca

cab

cba

Where am I going wrong here? How can I think about this differently to come up with the solution?

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!

解决方案

There you go (recursive permutation):

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')

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'))

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值