python回溯法实现数组全排列输出实例分析

WBOY
Release: 2016-06-06 11:22:37
Original
1371 people have browsed it

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

全排列解释:从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列。当m=n时所有的排列情况叫全排列。

from sys import stdout
#code from http://www.bitsCN.com/
def perm(li, start, end):
  if(start == end):
    for elem in li:
      stdout.write(elem)
    print ''
  else:
    for i in range(start, end):
      li[start], li[i] = li[i], li[start]
      perm(li, start+1, end)
      li[i], li[start] = li[start], li[i]
if __name__ == '__main__':
  li = ['a','b','c','d']
  perm(li, 0, len(li))
Copy after login

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!