zoukankan      html  css  js  c++  java
  • python非递归全排列

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

     1 def getArrayInsertCharToStr(STR,CHAR):
     2     arr =[]
     3     s_len = len(STR)
     4     index =0
     5     while index <= s_len:
     6         #分割字符串
     7         arr.append(STR[:index]+CHAR+STR[index:s_len])
     8         index = index + 1
     9     return arr    
    10 
    11 def getArrayInsertCharToArray(array,CHAR):
    12     index = 0
    13     re_array = []
    14     while index < len(array):
    15         re_array = re_array + getArrayInsertCharToStr(array[index],CHAR)
    16         index = index + 1
    17     return re_array             
    18 
    19 def getPermutation(STR):
    20         resultArr = [STR[0]]
    21         for item in STR[1:]:
    22             resultArr = getArrayInsertCharToArray(resultArr,item)
    23         return     resultArr
    24 
    25 
    26 print(getPermutation('abc'))    
  • 相关阅读:
    laravel数据库配置
    mysql中utf8和utf8mb4区别
    laravel中artisan的用法
    laravel项目composer安装
    Linux 文件描述符
    Centos 7/8 SELinux
    Centos 7/8 高级磁盘管理技术
    Centos 7/8 搭建NFS Server
    Centos 7/8 日志管理
    Centos 7/8 Chronyd时间同步
  • 原文地址:https://www.cnblogs.com/pixs-union/p/6061055.html
Copyright © 2011-2022 走看看