SoFunction
Updated on 2024-12-20

An introduction to python outputting all permutations of list elements

Example:

c', 'b'] ['b', 'a', 'c'] ['b', 'c', 'a'] [ 'c', 'a', 'b'] ['c', 'b', 'a']

Method 1: Implemented using recursion

def permutation(li):
  len_list = len(li)
  if len_list == 1:
    return li

  result = []
  for i in range(len_list):
    res_list = li[:i] + li[i+1:]
    s = li[i]
    per_result = permutation(res_list)
    if len(per_result) == 1:
      (li[i:i + 1] + per_result)
    else:
      result += [[s] + j for j in per_result]
  return result

Method 2: Utilizing python's own modules

import itertools

def permutation(li):
  print(list((li)))

Additional extensions: python implementation of a full permutation of four numbers

First we use the regular practice of cyclic exchange completion.

lst = [1, 3, 5, 8]

for i in range(0, len(lst)):
  lst[i], lst[0] = lst[0], lst[i]
  for j in range(1, len(lst)):
    lst[j], lst[1] = lst[1], lst[j]
    for h in range(2, len(lst)):
      print(lst)
    lst[j], lst[1] = lst[1], lst[j]
  lst[i], lst[0] = lst[0], lst[i]

If the list is longer, more elements, the above conventional method to achieve a more strenuous, the following we use recursive way to achieve.

def permutations(position):
  if position == len(lst) - 1:
    print(lst)
  else:
    for index in range(position, len(lst)):
      lst[index], lst[position] = lst[position], lst[index]
      permutations(position+1)
      lst[index], lst[position] = lst[position], lst[index]
permutations(0) 

The above article is a brief introduction to python output list elements of all the arrangement of the form is all I share with you, I hope to give you a reference, and I hope you support me more.