python output list element forms all permutations

E.g:

[‘a', ‘b', ‘c'] 输出 [‘a', ‘b', ‘c'] [‘a', ‘c', ‘b'] [‘b', ‘a', ‘c'] [‘b', ‘c', ‘a'] [‘c', ‘a', ‘b'] [‘c', ‘b', ‘a']
Method 1: Use a recursive manner
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:
      result.append(li[i:i + 1] + per_result)
    else:
      result += [[s] + j for j in per_result]
  return result
Method 2: Using the module comes python
import itertools
 
def permutation(li):
  print(list(itertools.permutations(li)))
Supplementary expand: python achieve full array of four numbers

First, we use the conventional approach, the cycle exchange is completed.

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 long, more elements than the conventional way to achieve it is more difficult, and we use the following recursive manner.

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)

On this form all permutations of the above python output list element hope to give you a reference.

Guess you like

Origin www.cnblogs.com/bug777/p/12468429.html