nombre_perm.py

Created by nicolas-patrois

Created on July 23, 2020

476 Bytes

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]))

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.