Skip to content

Instantly share code, notes, and snippets.

@ThiagosLima
Created August 14, 2020 15:51
Show Gist options
  • Save ThiagosLima/e6384298fbf6e79772860ae23039cfd0 to your computer and use it in GitHub Desktop.
Save ThiagosLima/e6384298fbf6e79772860ae23039cfd0 to your computer and use it in GitHub Desktop.
Study of the implementation of factorial
"""Study of the implementation of factorial"""
import pytest
from functools import reduce
def recursive_factorial(n):
"""Given a number n, return the factorial of n"""
if n == 0:
return 1
return n * recursive_factorial(n - 1)
def tail_factorial(n, factorial=1):
"""Factorial implementation with tail recursion"""
if n == 0:
return factorial
return tail_factorial(n-1, n * factorial)
def reduce_factorial(n):
"""Factorial implementation with reduce"""
numbers = range(n, 0, -1)
return reduce(lambda factorial, number: factorial * number, numbers, 1)
def for_factorial(n):
"""Factorial implementation with for"""
factorial = 1
for number in range(n, 0, -1):
factorial *= number
return factorial
def while_factorial(n):
"""Factorial implementation with while"""
factorial = 1
while n > 0:
factorial *= n
n -= 1
return factorial
@pytest.mark.parametrize('given, expect', [(0, 1),
(1, 1),
(2, 2),
(3, 6),
(4, 24),
(5, 120)])
def test_factorial(given, expect):
assert recursive_factorial(given) == expect
assert tail_factorial(given) == expect
assert reduce_factorial(given) == expect
assert for_factorial(given) == expect
assert while_factorial(given) == expect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment