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

后端 未结 7 823
既然无缘
既然无缘 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:26

    You can use cycle from itertools to alternate +/-

    >>> from itertools import cycle
    >>> data = [*range(1, 5)]
    >>> sum(i * s for i, s in zip(data, cycle([1, -1])))
    -2
    

提交回复
热议问题