Produit des entiers successifs
Exercice
Compléter la fonction factorielle
répondant à la spécification donnée dans la chaîne de documentation.
def factorielle(n):
"""Signature factorielle(n:int)->int
Précondition : n >= 0
Postcondition :
renvoie 1 si n == 0 ou le produit
des entiers successifs entre 1 et n
"""
#précondition
assert n >= 0
#à compléter
def factorielle(n): backslash_newline """Signature factorielle(n:int)->intbackslash_newline Précondition : n >= 0backslash_newline Postcondition : backslash_newline renvoie 1 si n == 0 ou le produit backslash_newline des entiers successifs entre 1 et n backslash_newline """ backslash_newline #préconditionbackslash_newline assert n >= 0backslash_newline #à compléterbackslash_newlinebackslash_newline# Solution 1backslash_newlinebackslash_newlinedef factorielle(n): backslash_newline """Signature factorielle(n:int)->intbackslash_newline Précondition : n >= 0backslash_newline Postcondition : backslash_newline renvoie 1 si n == 0 ou le produit backslash_newline des entiers successifs entre 1 et n backslash_newline """ backslash_newline #préconditionbackslash_newline assert n >= 0backslash_newline p = 1backslash_newline for k in range(2, n + 1):backslash_newline p = p * kbackslash_newline return pbackslash_newlinebackslash_newline# Solution 2 (Paradigme fonctionnel niveau terminale)backslash_newlinefrom functools import reduce backslash_newlinebackslash_newlinedef produit(x, y):backslash_newline return x * ybackslash_newlinebackslash_newlinedef factorielle2(n):backslash_newline assert n >= 0backslash_newline return reduce(produit, range(1, n + 1), 1)backslash_newlinebackslash_newlinebackslash_newline