In Python habe ich tatsächlich "permutations ()" in "itertools" implementiert. Ich habe nichts so Anspruchsvolles wie das Original implementiert, aber es spuckt alle grundlegenden ungedeckten Sequenzkombinationen aus.
Der Autor ist ein Kindergartenabsolvent, bitte verzeihen Sie mir etwaige Fehler im Artikel.
Da wir der Lesbarkeit von Code Priorität einräumen, gibt es einige Teile, die redundant geschrieben sind.
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)})
#Ergebnis(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)
#Die nxlist, die als Argument für den Aufruf der Wiederholungsfunktion übergeben wird, ist proportional zur Zunahme von x
[2,3,4]
[3,4]
[4]
#Es sieht aus wie
Es wird tatsächlich wie folgt verarbeitet
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]]
Es ist besser, "itertools" zu verwenden.
Recommended Posts