Calculate the factorial of a number and a list of numbers in reverse order

Question 1: Calculation factorial of a number, but also a full permutation problem.

For example: the numbers 1, 2, in accordance with the different elements in a row, a total of how many rows of law?

3 * 2 * 1 = 6. 3 factorial is digital.

So how to use the program to achieve it?

def factorial(num):
    """
    Recursive algorithm
    : A stop:
    :return:
    """
    if num == 1:
        return 1
    return num * factorial(num - 1)
Factorial recursive algorithm

In a recursive function, because the cost will be a function of the stack frame, so it's not as good as non-operating results recursive functions.

def factorial1(num):
    """
    Non-recursive algorithm
    : A stop:
    :return:
    """
    res = 1
    while num > 0:
        a * = whether
        Surely - = 1
     return business
Factorial cycle to achieve

Question 2: Calculate the number of a reverse sequence.

Inverse number: In one arrangement, if the longitudinal position of a pair of numbers in reverse order of magnitude, i.e. the number greater than the number in front of the latter, they are called a reverse order. A reverse arrangement on the total number of the called number in reverse order. All total a reverse arrangement is called this number in reverse order. That is, for n different elements, there is a first predetermined standard sequence between elements (e.g. n different natural numbers, can be considerably small to predetermined standard order), then any one of the n elements are arranged in a when an order in the order of two standard elements are different, they say there is a reverse order. All total a reverse arrangement is called this number in reverse order.

def get_reverse_num(lst):
    res = 0
    for i in range(len(lst)):
        s = 0
        for j in range(i):
            if lst[j] > lst[i]:
                s += 1
        res += s
    return res
Inverse number of a queue

 

Guess you like

Origin www.cnblogs.com/walle-zhao/p/11687570.html