python 写的两种打印全排列的方法速度对比

来源:互联网 发布:创业软件办公平台 编辑:程序博客网 时间:2024/06/12 21:39

 方法一:

max = 6
index = [0]*max
from time import clock
start=clock()

 

while True:
    candi = range(0,max)

    for i in range(1,max+1):
        print candi.pop(index[-i]),
    print ''

    index[1] += 1
    i = 1
    while i < max-1 and index[i] > i:
        index[i] = 0
        index[i+1] += 1
        i+=1
    if index[-1] >= max:
        break

 

finish=clock()
print (finish-start)

方法二:

def myprint(a,offset,needPrint):
    if needPrint:
        print a
    if len(a) == 1:
        return
    for t in range(offset,len(a)):
        te = a.pop(len(a)-1)
        a.insert(0,te)
        myprint(a,offset+1,t != len(a) -1)

from time import clock
start=clock()
a = [0,1,2,3,4,5]
myprint(a,0,True)
finish=clock()
print (finish-start)

方法一是从网上找的非递归的方法,使用的是统计学的方法,方法二是递归调用方法,如果方法二的换位置自己写的话,用时差不多,如果使用上述方法写的话,大家看看时间吧:

 

原创粉丝点击