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