equal
deleted
inserted
replaced
|
1 """ |
|
2 This is the "example" module. |
|
3 |
|
4 The example module supplies one function, factorial(). For example, |
|
5 |
|
6 >>> factorial(5) |
|
7 120 |
|
8 """ |
|
9 |
|
10 def factorial(n): |
|
11 """Return the factorial of n, an exact integer >= 0. |
|
12 |
|
13 If the result is small enough to fit in an int, return an int. |
|
14 Else return a long. |
|
15 |
|
16 >>> [factorial(n) for n in range(6)] |
|
17 [1, 1, 2, 6, 24, 120] |
|
18 >>> [factorial(long(n)) for n in range(6)] |
|
19 [1, 1, 2, 6, 24, 120] |
|
20 >>> factorial(30) |
|
21 265252859812191058636308480000000L |
|
22 >>> factorial(30L) |
|
23 265252859812191058636308480000000L |
|
24 >>> factorial(-1) |
|
25 Traceback (most recent call last): |
|
26 ... |
|
27 ValueError: n must be >= 0 |
|
28 |
|
29 Factorials of floats are OK, but the float must be an exact integer: |
|
30 >>> factorial(30.1) |
|
31 Traceback (most recent call last): |
|
32 ... |
|
33 ValueError: n must be exact integer |
|
34 >>> factorial(30.0) |
|
35 265252859812191058636308480000000L |
|
36 |
|
37 It must also not be ridiculously large: |
|
38 >>> factorial(1e100) |
|
39 Traceback (most recent call last): |
|
40 ... |
|
41 OverflowError: n too large |
|
42 """ |
|
43 |
|
44 import math |
|
45 if not n >= 0: |
|
46 raise ValueError("n must be >= 0") |
|
47 if math.floor(n) != n: |
|
48 raise ValueError("n must be exact integer") |
|
49 if n+1 == n: # catch a value like 1e300 |
|
50 raise OverflowError("n too large") |
|
51 result = 1 |
|
52 factor = 2 |
|
53 while factor <= n: |
|
54 result *= factor |
|
55 factor += 1 |
|
56 return result |
|
57 |
|
58 |
|
59 if __name__ == "__main__": |
|
60 import doctest |
|
61 doctest.testmod() |
|
62 |