Donne le numéro d’une permutation de (0,1,2,…) dans l’ordre lexicographique et inversement.
def fact(n): p=1 for i in range(1,n+1): p*=i return p def num2perm(m,n): l=list(range(n)) p=fact(n) for i in range(n,0,-1): m%=p p//=i q=m//p l=l[:q]+l[q+1:]+l[q:q+1] return l def perm2num(p): pp=list(p) p1=sorted(p) r=0 for i in range(len(pp)): d=p1.index(pp[i]) r+=d*fact(len(pp)-i-1) del p1[d] return r if __name__=="__main__": print(num2perm(1234567,8)) print(perm2num([0,8,1,5,4,3,6,2,7]))