comparison python/example/factorial.py @ 784:47a434dd5068

example: factorial using reduce
author Jeff Hammel <k0scist@gmail.com>
date Thu, 01 Sep 2016 15:15:23 -0700
parents
children
comparison
equal deleted inserted replaced
783:d564f7ad8294 784:47a434dd5068
1 #!/usr/bin/env python
2 """how many 0s are in a factorial"""
3
4 import argparse
5 import sys
6
7 def factorial(N):
8 """factorial of `N`"""
9 if N == 1:
10 return 1
11 return reduce(int.__mul__, range(2, N+1))
12
13 def factorial_zeros(N):
14 """how many 0s are in a factorial?"""
15
16 return N/5
17
18 def main(args=sys.argv[1:]):
19 """CLI"""
20
21 parser = argparse.ArgumentParser(description=__doc__)
22 parser.add_argument('N', type=int, nargs='+')
23 options = parser.parse_args(args)
24
25 # sanity
26 if any([i < 1 for i in options.N]):
27 parser.error("Input values must be >= 1")
28
29 for i in options.N:
30 f = factorial(i)
31 print f
32
33 if __name__ == '__main__':
34 main()