Home > Software engineering >  How do I make a function that adds once and subtract once for every number in the list?
How do I make a function that adds once and subtract once for every number in the list?

Time:10-09

This is my code, but I figured out that it only works if the numbers are 'even and odd in that order' so, How do I create a function that adds and then subtracts for every number in the list, so like if my list is 1,3,4,5 then the output is 1 3-4 5 or if my list is 4,6,7,4,5,3 then the output would be 4 6-7 4-5 3... please help

def alt_sum(lst):
    total = 0
    for i, value in enumerate(lst):
        if i % 2 == 0:
            total  = value
        else:
            total -= value
    return total

print(alt_sum([3, 4, 5, 8]))

CodePudding user response:

If the index is greater than 0 and an even number, take the negative value, and then add.

def alt_sum(lst):
    alt_lst = [-v if (i % 2 == 0 and i > 0) else v for i, v in enumerate(lst)]
    # print(alt_lst)
    return sum(alt_lst)


print(alt_sum([3, 4, 5, 8]))

CodePudding user response:

your explanation and sample intput/output differs.
your code is right by your explanation if you meant even and odd in that order as index, but is wrong based on sample input/output. Heres what should be based on sample input/output:

def alt_sum(lst):
    total = lst[0]
    for i in range(1,lst):
        if i % 2 == 0:
            total -= lst[i]
        else:
            total  = lst[i]
    return total

print(alt_sum([3, 4, 5, 8]))
  • Related