Écrire une fonction python récursive :
| Entrée | Une liste de nombres. |
|---|---|
| Sortie | True si les nombres de la liste sont tous distincts, False sinon. |
- version itérative
- version récursive
def tousDistincts(L) :
for i in range(0,len(L)-1) :
for j in range(i+1, len(L)) :
if L[i] == L[j] : return False
return True
print(tousDistincts( [2,3,6,2] ))
print(tousDistincts( [2,3,6,7] ))
ou plus concis avec les possibilités python :
def tousDistincts(L) :
for i in range(0,len(L)-1) :
if L[i] in L[i+1:] : return False
return True
print(tousDistincts( [2,3,6,2] ))
print(tousDistincts( [2,3,6,7] ))
print(tousDistincts( [ ] ))
On traduit la version itérative en récursif :
def tousDistincts(L, i = 0, j = 1) :
if i >= len(L)-1 : return True
else :
if j == len(L) : return tousDistincts(L, i+1, i+2)
else :
if L[i] == L[j] : return False
else : return tousDistincts(L, i, j+1)
print(tousDistincts( [2,3,6,2] ))
print(tousDistincts( [2,3,6,7] ))
print(tousDistincts( [] ))
ou encore :
def estDansListe( x, L) :
""" retourne True si x est dans L, False sinon."""
if L == [] : return False
else : return (x == L[0]) or estDansListe( x, L[1:] )
def tousDifferents(L) :
return (L == []) or ( not( estDansListe(L[0], L[1:]) ) and tousDifferents(L[1:]) )
print(tousDifferents([2,3,6,5,2,1]))
print(tousDifferents([2,3,6,5,15,1]))