python algorithm - permutation and combination

Permutations

1. Recursion

1. call yourself

2. Find an exit condition

 

2. Full permutation: For a given set of data, give a combination of permutations containing all data

1:1

1,2:[[1,2],[2,1]]

1,2,3:【【1,2,3】,【1,3,2】,【2,1,3】,

【2,3,1】,【3,2,1】,【3,1,2】】

 

3. Full permutation of 1,2,3 -- "[2,3]-"[2]

Rule: full permutation of [2,3] starting with 1 + full permutation of [1,3] starting with 2 + full permutation of [1,2] starting with 3

-》

Starting with 1 (full permutation of [3] starting with 2 + full permutation of [2] starting with 3) + all permutation starting with 2 (full permutation of [3] starting with 1 + starting with 3 The full permutation of [1]) + the full permutation of the leading 3 (the full permutation of [2] starting with 1 + the full permutation of [1] starting with 2)

 

 

Exercise 2: When there is only one number, what is the number of its full permutations?

Answer: 1

[2] ->[[2]]

[2,3] -》[[2,3],[3,2]]

When expressing full arrangement, we are accustomed to using a list to express

 

Fourth, the full permutation algorithm:

Find the full permutation of n numbers:

1. Extract each number by traversal, and find the full permutation of the remaining n-1 numbers

2. For the full permutation of n-1 numbers, extract a number and find the full permutation of the remaining n-2 numbers

3. Repeat the above steps until the number of digits becomes 1, which satisfies the recursive exit condition.

4. The sum of all the above permutations is the final full permutation.

 

Algorithm implementation:

# encoding=utf-8

 

def perm(listVar):

    if len(listVar) == 1 :

        return [listVar]

    retlist = []

    for i in xrange(len(listVar)):

        #Get a new list with the element pointed to by i removed from the list 

        restList = listVar[:i] + listVar[i+1 :]

        # 1

        #perm([2,3])-> [[2,3],[3,2]]

        # 1 is added to the result of perm(2,3) 

        perResult = perm(restList)

        for x in perResult:

            #Exercise : Can this line of code be written like this and why?

            # retlist.append(listVar[i]+x)

            retlist.append(listVar[i:i+1]+x)

    return retlist

 

if __name__ == '__main__':

    print perm([1,2,3])

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325766613&siteId=291194637
Recommended