Created
August 9, 2018 18:53
-
-
Save ripiuk/ef5275ccf7c079bf92f589a5c7ac1eeb to your computer and use it in GitHub Desktop.
Factorial calculation implementation with python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import clock | |
from collections import namedtuple | |
FACTORIAL_NUMBER = 12 | |
def factorial(x: int) -> int: | |
if x < 1: | |
raise Exception('The number should be grater than 1') | |
res = 1 | |
for i in range(1, x + 1): | |
res *= i | |
return res | |
def recursive_factorial(x: int) -> int: | |
if x == 1: | |
return 1 | |
elif x < 1: | |
raise Exception('The number should be grater than 1') | |
return x * factorial(x - 1) | |
def print_results(functions: list, *args) -> None: | |
Output = namedtuple('Output', ['func_name', 'result', 'time']) | |
title = Output('Function', 'Result', 'Time') | |
results = [title] | |
for func in functions: | |
search_start = clock() | |
res = func(*args) | |
search_time = clock() - search_start | |
results.append(Output(func.__name__, res, search_time)) | |
func_name_column_size = max([len(str(result.func_name)) for result in results]) | |
res_column_size = max([len(str(result.result)) for result in results]) | |
time_column_size = max([len(str(result.time)) for result in results]) | |
for _name, _result, _time in results: | |
print(f'{_name:<{func_name_column_size}} | {str(_result):<{res_column_size}} | ' | |
f'{_time:<{time_column_size}}') | |
if __name__ == "__main__": | |
print_results([factorial, recursive_factorial], FACTORIAL_NUMBER) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment