#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Created on Sat Dec 3 18:16:57 2016 @author: taylor@mst.edu """ # %% Iterative Factorial using loops (imperative), accumulate pattern def fact_loop(n: int) -> int: """ Computes the factorial of n, returns n. """ total = 1 for i in range(1, n + 1): total *= i return total print(fact_loop(5)) # %% tail recursive factorial def fact_rec_tail(n: int) -> int: """ Computes the factorial of n, returns n. One way of defaulting value, which hides the details. """ def loop(total: int, i: int) -> int: if i < n + 1: return loop(total * i, i + 1) else: return total return loop(1, 1) print(fact_rec_tail(5)) # %% tail recursive factorial def fact_rec_tail2(n: int, total: int = 1, i: int = 1) -> int: """ Computes the factorial of n, returns n. Another way of defaulting values. """ if i < n + 1: return fact_rec_tail2(n, total * i, i + 1) else: return total print(fact_rec_tail2(5))