Some_acctg_guy
Some_acctg_guy

Reputation: 105

Creating a function with variable-length arguments python

I need create a simple function that computes the cumulative sum (every value in the input tuple should be replaced by the sum of all values before and including the current value, thus (1, 2, 3) becomes (1, 3, 6)) of its arguments, which you can assume are passed by value. Use a variable-length parameter to access these values and return the result as a tuple.

My thought is to use a for loop, but I don't know how to reference the preceding item in the variable-length argument. Below is what I have so far.

def simple_tuple_func(*args):
#  Compute cumulative sum of each value
    print(type(args))
    for idx in args:
        **idx += {itm}**
simple_tuple_func(1,2,3)

The line I have bolded is where I am not sure how to reference the preceding item in the tuple(or list, dictionary, or any other item given as an argument for the function. I believe it would work if I had that line correct?

Upvotes: 3

Views: 1002

Answers (2)

Netwave
Netwave

Reputation: 42756

Simply use itertools.accumulate:

def simple_tuple_func(*args):
    return tuple(itertools.accumulate(args, lambda x, y: x+y))

Or with a loop:

def simple_tuple_func(*args):
    res = []
    if not args:
      return res
    accum, *tail = args #unpacking, accum will take first element and tail de rest elements in the args tuple
    for e in tail:
        res.append(accum)
        accum += e
    res.append(accum)
    return tuple(res)

Here you have the live example

Upvotes: 1

blhsing
blhsing

Reputation: 107005

You can append the cumulative sums to a separate list for output, so that you can use index -1 to access to preceding cumulative sum:

def simple_tuple_func(*args):
    cumulative_sums = []
    for i in args:
        cumulative_sums.append((cumulative_sums[-1] if cumulative_sums else 0) + i)
    return tuple(cumulative_sums)

so that:

simple_tuple_func(1,2,3)

would return:

(1, 3, 6)

Upvotes: 1

Related Questions