Search code examples
pythonvariable-length

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?


Solution

  • 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)