In a homework set I'm working on, I've come across the following question, which I am having trouble answering in a Python-3 function:
"Write a function alternate : int list -> int that takes a list of numbers and adds them with alternating sign. For example alternate [1,2,3,4] = 1 - 2 + 3 - 4 = -2."
Full disclosure, the question was written with Standard ML in mind but I have been attempting to learn Python and came across the question. I'm imagining it involves some combination of:
splitting the list,
if [i] % 2 == 0:
and then concatenating the alternate plus and minus signs.
def alternate(l):
return sum(l[::2]) - sum(l[1::2])
Take the sum of all the even indexed elements and subtract the sum of all the odd indexed elements. Empty lists sum to 0
so it coincidently handles lists of length 0 or 1 without code specifically for those cases.
References:
sum()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With