En Python, j'ai en fait implémenté permutations ()
dans ʻitertools`.
Je n'ai rien implémenté d'aussi sophistiqué que l'original, mais il crache toutes les combinaisons de séquences de base découvertes.
L'auteur est diplômé de la maternelle, alors pardonnez-moi toute erreur dans l'article.
Puisque nous accordons la priorité à la lisibilité du code, certaines parties sont écrites de manière redondante.
def permutations(source):
length = len(source)
if length == 1:
return [source]
result = []
for x in range(length):
nxarray = source[x]
nxlist = source[0:x] + source[x+1:length]
for y in permutations(nxlist):
nyarray = [nxarray] + y
result.append(nyarray)
return result
numbers = [1, 2, 3]
print(permutations(numbers)})
#résultat(6)
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
source = [1,2,3,4]
# for x in range(source)
#La nxlist passée en argument à l'appel de la fonction de récurrence est proportionnelle à l'augmentation de x
[2,3,4]
[3,4]
[4]
#On dirait
Il est en fait traité comme suit
Called with: [1, 2, 3]
-> nxlist: [] + [2, 3] = [2, 3]
Called with: [2, 3]
-> nxlist: [] + [3] = [3]
Called with: [3]
-> y: [3]
-> stored: [2, 3]
-> nxlist: [2] + [] = [2]
Called with: [2]
-> y: [2]
-> stored: [3, 2]
-> Result: [[2, 3], [3, 2]]
-> y: [2, 3]
-> stored: [1, 2, 3]
-> y: [3, 2]
-> stored: [1, 3, 2]
-> nxlist: [1] + [3] = [1, 3]
Called with: [1, 3]
-> nxlist: [] + [3] = [3]
Called with: [3]
-> y: [3]
-> stored: [1, 3]
-> nxlist: [1] + [] = [1]
Called with: [1]
-> y: [1]
-> stored: [3, 1]
-> Result: [[1, 3], [3, 1]]
-> y: [1, 3]
-> stored: [2, 1, 3]
-> y: [3, 1]
-> stored: [2, 3, 1]
-> nxlist: [1, 2] + [] = [1, 2]
Called with: [1, 2]
-> nxlist: [] + [2] = [2]
Called with: [2]
-> y: [2]
-> stored: [1, 2]
-> nxlist: [1] + [] = [1]
Called with: [1]
-> y: [1]
-> stored: [2, 1]
-> Result: [[1, 2], [2, 1]]
-> y: [1, 2]
-> stored: [3, 1, 2]
-> y: [2, 1]
-> stored: [3, 2, 1]
-> Result: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Final Result: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Il vaut mieux utiliser «itertools».
Recommended Posts