#function: 1到n的排列组合
#author:whyenglish
#e-mail:0316140111@mail.nuc.edu.cn
#思路:
#因为python每次可产生一随机数,
#让其产生n个随机数到一个list1里
#range(1,n+1)产生1到n,放在list2里
#list2中元素为key, list1中元素为value, 对应到mydict里
#按照values排序,打乱keys, 产生一种排列disorder
#不断产生disorder, 放入ok, 直到ok里有n! 个各不雷同的disorder
import random
from operator import itemgetter
import sys
def sortdictbyvalue(dict): #按字典values排序
dict_list=sorted(dict.items(),key=itemgetter(1))
output=[]
for i in dict_list:
output.append(i[0])
return output
def disorder(num): # 产生一个disorder
#myrand will get a series of rand-number
myrand=[]
for i in range(1,num+1):
r=random.randint(1,num)
myrand.append(r)
#mirror range(1,num) to myrand, that is, mydict
mydict={}
index=0
mykeys=range(1,num+1)
for key in mykeys:
mydict[mykeys[index]]=myrand[index]
index=index+1
#sort mydict by value, so mykeys isn't in order
output=sortdictbyvalue(mydict)
return output
def fact(num): #计算n!
if num==1 or num==0:
return 1
else:
output=num*fact(num-1)
return output
def ok(num): # 产生n!个disorder
indu=0
induok=[]
while indu < fact(num):
test=disorder(num)
if test not in induok:
induok.append(test)
indu=indu+1
print induok
if __name__=="__main__":
num=int(sys.argv[1])
ok(num)