当前位置: 移动技术网 > IT编程>脚本编程>Python > 递归实现全排列python

递归实现全排列python

2019年07月06日  | 移动技术网IT编程  | 我要评论

北京家具网购,全勇先霍尔瓦特大街,三体2txt

python递归实现"abcd"字符串全排列

1.保持a不动,动bcd
2.保持b不动,动cd
3.保持c不动,动d

def pailie(head="",string=""):
    if len(string)>1:
        for father_string in string:
            pailie(head+father_string,string.replace(father_string,"")) #关键一点:将头和尾全部传下去
    else:
        print(head+string)


pailie(string="abcd")

python递归实现"abad"字符串全排列

与上一个两个不同,一是,第一个a排完顺序后,下一个a不能再排,二是替换的时候不能把重复的也替换掉

def pailie(head="",string=""):
    if len(string)>1:
        for num,father_string in enumerate(string):
            if father_string in string[0:num]:#如果字符与前面的重复说明拍过顺序了
                continue
            pailie(head+father_string,string.replace(father_string,"",1))#只能替换一次
    else:
        print(head+string)

pailie(string="abca")

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网