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

后端 未结 7 802
既然无缘
既然无缘 2020-12-10 07:40

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 fun

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 08:10

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

提交回复
热议问题