Mercurial > hg > config
changeset 784:47a434dd5068
example: factorial using reduce
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Thu, 01 Sep 2016 15:15:23 -0700 |
parents | d564f7ad8294 |
children | 205dd903e4c8 |
files | python/example/factorial.py |
diffstat | 1 files changed, 34 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/python/example/factorial.py Thu Sep 01 15:15:23 2016 -0700 @@ -0,0 +1,34 @@ +#!/usr/bin/env python +"""how many 0s are in a factorial""" + +import argparse +import sys + +def factorial(N): + """factorial of `N`""" + if N == 1: + return 1 + return reduce(int.__mul__, range(2, N+1)) + +def factorial_zeros(N): + """how many 0s are in a factorial?""" + + return N/5 + +def main(args=sys.argv[1:]): + """CLI""" + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('N', type=int, nargs='+') + options = parser.parse_args(args) + + # sanity + if any([i < 1 for i in options.N]): + parser.error("Input values must be >= 1") + + for i in options.N: + f = factorial(i) + print f + +if __name__ == '__main__': + main()