Home  >  Article  >  Backend Development  >  python通过yield实现数组全排列的方法

python通过yield实现数组全排列的方法

WBOY
WBOYOriginal
2016-06-06 11:22:291508browse

本文实例讲述了python通过yield实现数组全排列的方法。分享给大家供大家参考。具体分析如下:

从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列。当m=n时所有的排列情况叫全排列。
这段代码用到了yield方法,全排列速度加倍

def perm(arr, pos = 0):
  if pos == len(arr):
    yield arr
  for i in range(pos, len(arr)):
    arr[pos], arr[i] = arr[i], arr[pos]
    for _ in perm(arr, pos + 1): yield _
    arr[pos], arr[i] = arr[i], arr[pos]
for i in perm([1,2,3,4]):
  print i

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn