Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 372
Some_acctg_guy Avatar asked Apr 08 '26 23:04

Some_acctg_guy


2 Answers

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)
like image 139
blhsing Avatar answered Apr 13 '26 22:04

blhsing


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

like image 21
Netwave Avatar answered Apr 14 '26 00:04

Netwave