forked from shwina/python-102
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathalgorithms.py
More file actions
72 lines (53 loc) · 2.3 KB
/
Copy pathalgorithms.py
File metadata and controls
72 lines (53 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# SPDX-FileCopyrightText: 2019-2021 Python201 Contributors
# SPDX-License-Identifier: MIT
"""Numerical algorithms."""
# type annotations
from typing import List
# standard libs
import sys
from argparse import ArgumentParser, FileType
# internal libs
from .core.logging import getLogger, initialize_logging
# module level logger
log = getLogger(__name__)
def cumulative_product(array: List[float]) -> List[float]:
"""
Compute the cumulative product of an array of numbers.
Parameters:
array (list): An array of numeric values.
Returns:
result (list): A list of the same shape as `array`.
Example:
>>> cumulative_product([1, 2, 3, 4, 5])
[1, 2, 6, 24, 120]
"""
result = list(array)
for i, value in enumerate(array[1:]):
result[i+1] = result[i] * value
sample = '[]' if not result else f'[..., {result[-1]:g}]'
log.debug(f'cumulative_product: length-{len(result)} array {sample}')
return result
def main() -> int:
"""Command line entry-point for `cumulative_product`."""
description = 'Compute the cumulative product of an array of numbers.'
parser = ArgumentParser(prog='cumprod', description=description)
parser.add_argument('-v', '--version', action='version', version='0.0.1')
parser.add_argument('infile', metavar='FILE', type=FileType(mode='r'),
default=sys.stdin,
help='input file path (default <stdin>)')
parser.add_argument('-o', '--output', dest='outfile', metavar='FILE',
default=sys.stdout, type=FileType(mode='w'),
help='output file path (default <stdout>)')
parser.add_argument('-l', '--last-only', action='store_true',
help='only keep the last value')
parser.add_argument('-d', '--debug', action='store_true',
help='show debugging messages')
cmdline = parser.parse_args()
# initialize logger for console output
initialize_logging('debug' if cmdline.debug else 'warning')
values = map(float, cmdline.infile)
result = cumulative_product(list(values))
# '%g' formatting automatically pretty-prints
start = -1 if cmdline.last_only else 0
print('\n'.join([f'{value:g}' for value in result[start:]]), file=cmdline.outfile)
return 0