Python实现全排列的打印

yipeiwu_com5年前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基本数据类型

int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647 在64位系统上,整数的位数为64位,取值范围为...

解决pytorch DataLoader num_workers出现的问题

解决pytorch DataLoader num_workers出现的问题

最近在学pytorch,在使用数据分批训练时在导入数据是使用了 DataLoader 在参数 num_workers的设置上使程序出现运行没有任何响应的结果 ,看看代码 import...

python开发之thread实现布朗运动的方法

python开发之thread实现布朗运动的方法

本文实例讲述了python开发之thread实现布朗运动的方法。分享给大家供大家参考,具体如下: 这里我将给大家介绍有关python中thread来实现布朗运动的一个例子 下面是运行效果...

Python使用微信SDK实现的微信支付功能示例

本文实例讲述了Python使用微信SDK实现的微信支付功能。分享给大家供大家参考,具体如下: 最近一段时间一直在搞微信平台开发,v3.37版本微信支付接口变化贼大,所以就看着php的de...

python3模拟实现xshell远程执行liunx命令的方法

python3模拟实现xshell远程执行liunx命令的方法

依赖包:pip install paramiko 源码demo: from time import * import paramiko # 定义一个类,表示一台远端linux主机 c...