In Python, I actually implemented permutations () in ʻitertools`.
I haven't implemented anything as sophisticated as the original, but it spits out all the basic uncovered permutation combinations.
The author is a kindergarten graduate, so please forgive me for any mistakes in the article.

Since code readability is prioritized, there are some redundant parts.
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)})
#result(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)
#The nxlist passed as an argument to the call to the recurrence function is proportional to the increase in x.
[2,3,4]
[3,4]
[4]
#It looks like
It is actually processed as follows
 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]]
It is better to use ʻitertools`.
Recommended Posts