doctests.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """
  2. Doctest example from the official Python documentation.
  3. https://docs.python.org/3/library/doctest.html
  4. """
  5. def factorial(n):
  6. """Return the factorial of n, an exact integer >= 0.
  7. >>> [factorial(n) for n in range(6)]
  8. [1, 1, 2, 6, 24, 120]
  9. >>> factorial(30)
  10. 265252859812191058636308480000000
  11. >>> factorial(-1)
  12. Traceback (most recent call last):
  13. ...
  14. ValueError: n must be >= 0
  15. Factorials of floats are OK, but the float must be an exact integer:
  16. >>> factorial(30.1)
  17. Traceback (most recent call last):
  18. ...
  19. ValueError: n must be exact integer
  20. >>> factorial(30.0)
  21. 265252859812191058636308480000000
  22. It must also not be ridiculously large:
  23. >>> factorial(1e100)
  24. Traceback (most recent call last):
  25. ...
  26. OverflowError: n too large
  27. """
  28. import math
  29. if not n >= 0:
  30. raise ValueError("n must be >= 0")
  31. if math.floor(n) != n:
  32. raise ValueError("n must be exact integer")
  33. if n+1 == n: # catch a value like 1e300
  34. raise OverflowError("n too large")
  35. result = 1
  36. factor = 2
  37. while factor <= n:
  38. result *= factor
  39. factor += 1
  40. return result