Flexible Python: Product of a List

How many different ways can we multiply the elements of a variable-length list in Python?

def iterative(args_list):
    j=1
    for i in args_list:
        j *= i
    return j

def recursive(args_list):
    if type(args_list) == int:
        return args_list
    elif len(args_list) == 0:
        return "empyt list"
    elif len(args_list) == 1:
        return args_list[0]
    else:
        return recurse(args_list[0]) * recurse(args_list[1:])

def with_operator(args_list):
    from operator import mul
    return reduce(mul, args_list)

def without_operator(args_list):
    return reduce(lambda x,y: x*y, args_list)

def numpy_prod(args_list):
    from numpy import prod
    return prod(args_list)

def log_sum_exp(args_list):
    from math import exp, log
    return exp(sum(map(log, args_list)))

def log_fsum_exp(args_list):
    from math import exp, log, fsum
    return exp(fsum(map(log, args_list)))

Any that I missed? Add them in the comments.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s