## 2014年4月3日木曜日

### Python - Functions and Generators(Computing factorials(recursive, functools module(reduce method), for loop, math module(factorial method)))

Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART III.(Functions and Generators)、Test Your Knowledge: Part IV Exercises 、12.(Computing factorials)を解いてみる。

その他参考書籍

12.(Computing factorials)

コード(BBEdit)

sample.py

```#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import functools
import math
import timeit

# 1 recursive
def func1(n):
if n <= 1:
return 1
return  n * func1(n - 1)

# 2 functools module, reduce method
def func2(n):
return functools.reduce((lambda x, y: x * y), range(1, n + 1))

# 3 iterative counter loop
def func3(n):
res = 1
for x in range(2, n + 1):
res *= x
return res

# 4 math module, factorial method
def func4(n):
return math.factorial(n)

funcs = [func1, func2, func3, func4]
for func in funcs:
print(func.__name__, func(10))

for func in funcs:
print(func.__name__,
min(timeit.repeat(stmt=lambda: func(10), repeat=3, number=100000)))
```

```\$ ./sample.py
func1 3628800
func2 3628800
func3 3628800
func4 3628800
func1 1.0081726789940149
func2 1.2377313239994692
func3 0.6970263260009233
func4 0.06130688500707038
\$
```