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

后端 未结 7 800
既然无缘
既然无缘 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
    >>>
    
    0 讨论(0)
  • 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()
    0 讨论(0)
  • 2020-12-10 08:11

    Here is one way using operator module:

    In [21]: from operator import pos, neg
    
    In [23]: ops = (pos, neg)
    
    In [24]: sum(ops[ind%2](value) for ind, value in enumerate(lst))
    Out[24]: -2
    
    0 讨论(0)
  • 2020-12-10 08:19
    my_list = range(3, 20, 2)
    sum(item * ((-1)**index) for index, item in enumerate(my_list))
    

    sum = 11 (result of 3-5+7-9+11-13+15-17+19)

    0 讨论(0)
  • 2020-12-10 08:22

    Although this already has an accepted answer I felt it would be better to also provide a solution that isn't a one-liner.

    def alt_sum(lst):
        total = 0
        for i, value in enumerate(lst):
            # checks if current index is odd or even
            # if even then add, if odd then subtract
            if i % 2 == 0:
                total += value
            else:
                total -= value
        return total
    
    >>> alt_sum([1, 2, 3, 4])
    -2
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题