Python实现全排列的打印

yipeiwu_com6年前Python基础

本文为大家分享了Python实现全排列的打印的代码,供大家参考,具体如下

问题:输入一个数字:3,打印它的全排列组合:123 132 213 231 312 321,并进行统计个数。

下面是Python的实现代码:

#!/usr/bin/env python
# -*- coding: <encoding name> -*- 
'''
全排列的demo
input : 3
output:123 132 213 231 312 321
'''
 
total = 0
 
def permutationCove(startIndex, n, numList):
  '''递归实现交换其中的两个。一直循环下去,直至startIndex == n
  '''
  global total
  if startIndex >= n:
    total += 1
    print numList
    return
    
  for item in range(startIndex, n):
    numList[startIndex], numList[item] = numList[item], numList[startIndex]
    permutationCove(startIndex + 1, n, numList )
    numList[startIndex], numList[item] = numList[item], numList[startIndex]
      
 
n = int(raw_input("please input your number:"))
startIndex = 0
total = 0
numList = [x for x in range(1,n+1)]
print '*' * 20
for item in range(0, n):
  numList[startIndex], numList[item] = numList[item], numList[startIndex]
  permutationCove(startIndex + 1, n, numList)
  numList[startIndex], numList[item] = numList[item], numList[startIndex]
 
print total

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python引用(import)某个模块提示没找到对应模块的解决方法

python引用(import)某个模块提示没找到对应模块的解决方法

自己检查了很多遍,自己写的每错,但是还是报没有找到对应python模块。目录结构如下图所示: __init__.py这个文件需要引入models下的todo_kanban.py文件。_...

用vue.js组件模拟v-model指令实例方法

1、问题描述 在使用v-model指令实现输入框数据双向绑定,输入值时对应的这个变量的值也随着变化;但是这里不允许使用v-model,需要写一个组件实现v-model指令效果 <...

python计算程序开始到程序结束的运行时间和程序运行的CPU时间

执行时间 方法1复制代码 代码如下:import datetimestarttime = datetime.datetime.now()#long runningendtime = da...

关于pytorch多GPU训练实例与性能对比分析

关于pytorch多GPU训练实例与性能对比分析

以下实验是我在百度公司实习的时候做的,记录下来留个小经验。 多GPU训练 cifar10_97.23 使用 run.sh 文件开始训练 cifar10_97.50 使用 run.4GPU...

python里 super类的工作原理详解

super 的工作原理如下: def super(cls, inst): mro = inst.__class__.mro() return mro[mro.index(cl...