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

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

    Not using fancy modules or operators since you are learning Python.

    >>> mylist = range(2,20,3)
    >>> mylist
    [2, 5, 8, 11, 14, 17]
    >>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
    -9
    >>>
    

    How it works?

    >>> mylist = range(2,20,3)
    >>> mylist
    [2, 5, 8, 11, 14, 17]
    

    enumerate(mylist, 1) - returns each item in the list and its index in the list starting from 1

    If the index is odd, then add the item. If the index is even add the negative of the item.

    if i%2:
      return item
    else:
      return -1*item
    

    Add everything using sum bulitin.

    >>> sum(item if i%2 else -1*item for i,item in enumerate(mylist, 1))
    -9
    >>>
    

提交回复
热议问题