python非递归全排列实现方法

yipeiwu_com6年前Python基础

刚刚开始学习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   resultArr


print(getPermutation('abc'))

以上这篇python非递归全排列实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

win7 下搭建sublime的python开发环境的配置方法

Step1:安装python和sublime Step2:给sublime安装package control,安装参见: 官网 Step3:配置安装路径 方式一:配置windows的Pa...

python使用scrapy发送post请求的坑

使用requests发送post请求 先来看看使用requests来发送post请求是多少好用,发送请求 Requests 简便的 API 意味着所有 HTTP 请求类型都是显而易见的...

python创建列表和向列表添加元素的实现方法

今天的学习内容是python中的列表的相关内容。 一.创建列表 1.创建一个普通列表 >>> tabulation1 = ['大圣','天蓬','卷帘'] >...

python将字符串以utf-8格式保存在txt文件中的方法

python将字符串以utf-8格式保存在txt文件中的方法

如下所示: #ltp_data 字符串 写进777.txt 1、 def save(filename, contents): fh = open(filename, 'w',...

tensorflow: 查看 tensor详细数值方法

问题 tensor详细数值 不能直接print打印: import tensorflow as tf x = tf.constant(1) print x 输出: Tensor...