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实现批量检测HTTP服务的状态

Python实现批量检测HTTP服务的状态

用Python实现批量测试一组url的可用性(可以包括HTTP状态、响应时间等)并统计出现不可用情况的次数和频率等。 类似的,这样的脚本可以判断某个服务的可用性,以及在众多的服务提供者中...

python+tkinter编写电脑桌面放大镜程序实例代码

python+tkinter编写电脑桌面放大镜程序实例代码

本文讲述的是通过python+tkinter编写一个简单桌面放大镜的代码示例,具体如下。 代码思路:首先全屏截图,然后在鼠标当前位置以小窗口进行二次截图,放大后再显示到鼠标左上角。 主要...

python flask安装和命令详解

Flask Web开发实战学习笔记 Flask简介 Flask是使用Python编写的Web微框架。Web框架可以让我们不用关 心底层的请求响应处理,更方便高效地编写Web程序。因为Fl...

Python tensorflow实现mnist手写数字识别示例【非卷积与卷积实现】

本文实例讲述了Python tensorflow实现mnist手写数字识别。分享给大家供大家参考,具体如下: 非卷积实现 import tensorflow as tf from t...

python选取特定列 pandas iloc,loc,icol的使用详解(列切片及行切片)

df是一个dataframe,列名为A B C D 具体值如下: A B C D 0 ss 小红 8 1 aa 小明 d 4 f f 6 ak 小紫 7 dataframe里的属性是不定...