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小波分析库Pywavelets的一点使用心得

浅谈Python小波分析库Pywavelets的一点使用心得

本文介绍了Python小波分析库Pywavelets,分享给大家,具体如下: # -*- coding: utf-8 -*- import numpy as np import m...

Python最火、R极具潜力 2017机器学习调查报告

Python最火、R极具潜力 2017机器学习调查报告

数据平台 Kaggle 近日发布了 2017 机器学习及数据科学调查报告,这也是 Kaggle 首次进行全行业调查。调查共收到超过 16000 份回复,受访内容包括最受欢迎的编程语言、不...

PyTorch加载预训练模型实例(pretrained)

使用预训练模型的代码如下: # 加载预训练模型 resNet50 = models.resnet50(pretrained=True) ResNet50 = ResNet(Bot...

Python 中的 import 机制之实现远程导入模块

Python 中的 import 机制之实现远程导入模块

所谓的模块导入( import ),是指在一个模块中使用另一个模块的代码的操作,它有利于代码的复用。 在 Python 中使用 import 关键字来实现这个操作,但不是唯一的方法,还有...

python 删除大文件中的某一行(最有效率的方法)

用 python 处理一个文本时,想要删除其中中某一行,常规的思路是先把文件读入内存,在内存中修改后再写入源文件。 但如果要处理一个很大的文本,比如GB级别的文本时,这种方法不仅需要占用...