def calculate_stats(values, **kwargs): ''' Takes a list of numbers (values) and computes some statistics, then returns either a specially-formatted string (perhaps suitable for writing to a file), a tuple of values, or a dictionary. store is used to specify the storage (and return) type: 'dict', 'list', or 'str' (default is list). If 'str' is chosen, then the additional options are: * delim: the delimiter to use to separate values (default=',') * endl: the end-of-line string to use (default='\\n') * incl_head: include a header line with the label for each column (True or False, default=False) as_type is used to convert the elements in the values collection into the specified type (default is float) ''' if not isinstance(values, (list, tuple, set)): raise TypeError('values must be a list, tuple, or set') to_type = kwargs.get('as_type', float) values = [to_type(v) for v in values] retval = [] labels = [] length = len(values) retval.append(length) labels.append('length') total = sum(values) retval.append(total) labels.append('total') retval.append(float(total) / length) labels.append('mean') smallest = min(values) retval.append(smallest) labels.append('min') largest = max(values) retval.append(largest) labels.append('max') retval.append(largest - smallest) labels.append('range') store = kwargs.get('store', list) if store in (dict, 'dict'): return dict(zip(labels, retval)) elif store in (str, 'str'): delim = kwargs.get('delim', ',') end = kwargs.get('endl', '\\n') output = '' if kwargs.get('incl_head', False): output += delim.join(labels) + end output += delim.join([str(v) for v in retval]) + end return output else: return labels, retval array = [5.4, 3.5, 7.1, -2.4] results1 = calculate_stats(array) print('results1 =', results1) print() results2 = calculate_stats(array, store=dict) print('results2 =', results2) print() results3 = calculate_stats(array, store=dict, as_type=int) print('results3 =', results3) print() results4 = calculate_stats(array, store=str, incl_head=True) print('results4 =', results4) def squared(x): return x*x results5 = calculate_stats(array, store=dict, as_type=lambda x: x*x) print('results5 =', results5) print()