首页 > 编程 > Python > 正文

python非递归全排列实现方法

2019-11-25 16:15:34
字体:
来源:转载
供稿:网友

刚刚开始学习python,当前看到了函数这一节。结合数组操作,写了个非递归的全排列生成。原理是插入法,也就是在一个有n个元素的已有排列中,后加入的元素,依次在前,中,后的每一个位置插入,生成n+1个新的全排列。因为Python切割数组或者字符串,以及合并比较方便,所以,程序会节省很多代码。

def getArrayInsertCharToStr(STR,CHAR):  arr =[]  s_len = len(STR)  index =0  while index <= s_len:    #分割字符串    arr.append(STR[:index]+CHAR+STR[index:s_len])    index = index + 1  return arr  def getArrayInsertCharToArray(array,CHAR):  index = 0  re_array = []  while index < len(array):    re_array = re_array + getArrayInsertCharToStr(array[index],CHAR)    index = index + 1  return re_array       def getPermutation(STR):    resultArr = [STR[0]]    for item in STR[1:]:      resultArr = getArrayInsertCharToArray(resultArr,item)    return   resultArrprint(getPermutation('abc'))

以上这篇python非递归全排列实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表