Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a function that alternates plus and minus signs between list indices

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.

like image 204
A. Chiasson Avatar asked Dec 27 '16 05:12

A. Chiasson


1 Answers

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:

  • list slice examples
  • sum()
like image 185
Ouroborus Avatar answered Sep 19 '22 12:09

Ouroborus