Python uses recursion to solve all-ranked digital examples _python

Source: Internet
Author: User

The first method: recursion

Copy Code code as follows:

def perms (elements):
If Len (elements) <=1:
Yield elements
Else
For Perm in Perms (elements[1:]):
For I in range (len (elements)):
Yield perm[:i] + elements[0:1] + perm[i:]

For item in list (perms [1, 2, 3,4]):
Print Item


Results
Copy Code code as follows:

[1, 2, 3, 4]
[2, 1, 3, 4]
[2, 3, 1, 4]
[2, 3, 4, 1]
[1, 3, 2, 4]
[3, 1, 2, 4]
[3, 2, 1, 4]
[3, 2, 4, 1]
[1, 3, 4, 2]
[3, 1, 4, 2]
[3, 4, 1, 2]
[3, 4, 2, 1]
[1, 2, 4, 3]
[2, 1, 4, 3]
[2, 4, 1, 3]
[2, 4, 3, 1]
[1, 4, 2, 3]
[4, 1, 2, 3]
[4, 2, 1, 3]
[4, 2, 3, 1]
[1, 4, 3, 2]
[4, 1, 3, 2]
[4, 3, 1, 2]
[4, 3, 2, 1]

Second method: Python standard library

Copy Code code as follows:

Import Itertools
Print List (Itertools.permutations ([1, 2, 3,4],3))

The source code is as follows:

Copy Code code as follows:

#coding: Utf-8
Import Itertools
Print List (Itertools.permutations ([1, 2, 3,4],3))

def perms (elements):
If Len (elements) <=1:
Yield elements
Else
For Perm in Perms (elements[1:]):
For I in range (len (elements)):
Yield perm[:i] + elements[0:1] + perm[i:]

For item in list (perms [1, 2, 3,4]):
Print Item

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.