Study notes (02): 21 days the Python clearance (Only Video Class) - Case practical operation: the definition of a function of computing N factorial

Learning immediately: https://edu.csdn.net/course/play/24797/282183?utm_source=blogtoedu

N factorial calculation is defined as a function

 

# Cycles --------------------------------- 
DEF testfun (n-): 
    R & lt =. 1 
    IF n-<. 1: 
        Print ( 'n is not less than. 1') 
        return 
    the else: 
        for I in Range (. 1, n-+. 1): 
            #. 1 * n-2 * n-. 3 * n- 
            R & lt * = I 
    return R & lt 


Print (testfun (. 5)) 
Print (testfun ( . 6)) 
Print (testfun (. 7)) 


# recursive --------------------------------- 
DEF testfun2 (n-) : 
    R & lt =. 1 
    IF n-<. 1: 
        Print ( 'n-not less than. 1') 
        return 
    elif n-==. 1: 
        return. 1 
    the else: 
        return testfun2 (n--. 1) * n- 


Print (testfun2 (. 5))  
Print (testfun2 (. 6 ))
Print (testfun2 (. 7 ))

# functools---------------------------
import functools


def funtools(x, y):
    return x * y


def testfun3(n):
    r = 1
    if n < 1:
        print('n 不能小于1')
        return
    else:
        return functools.reduce(funtools, range(1, n + 1))


print(testfun3(5))
print(testfun3(6))
print(testfun3(7))

# functools--lambda---------------------------
import functools


def testfun4(n):
    r = 1
    if n < 1:
        print('n 不能小于1')
        return
    else:
        return functools.reduce(lambda x, y: x * y, range(1, n + 1))


print(testfun4(5))
print(testfun4(6))
print(testfun4(7))
Published 25 original articles · won praise 4 · Views 613

Guess you like

Origin blog.csdn.net/happyk213/article/details/105126054