简体   繁体   中英

Python adding/subtracting sequence

Hi so i'm trying to make a function where I subtract the first number with the second and then add the third then subtract the fourth ie. x1-x2+x3-x4+x5-x6...

So far I have this, I can only add two variables, x and y. Was thinking of doing

>>> reduce(lambda x,y: (x-y) +x, [2,5,8,10]

Still not getting it

pretty simple stuff just confused..

In this very case it would be easier to use sums:

a = [2,5,8,10]
sum(a[::2])-sum(a[1::2])
-5

Use a multiplier that you revert to +- after each addition.

result = 0
mult = 1
for i in [2,5,8,10]:
    result += i*mult
    mult *= -1

You can keep track of the position (and thus whether to do + or - ) with enumerate , and you could use the fact that -1 2n is +1 and -1 2n+1 is -1 . Use this as a factor and sum all the terms.

>>> sum(e * (-1)**i for i, e in enumerate([2,5,8,10]))
-5

Or just using sum and a generator:

In [18]: xs
Out[18]: [1, 2, 3, 4, 5]

In [19]: def plusminus(iterable):
   ....:     for i, x in enumerate(iterable):
   ....:         if i%2 == 0:
   ....:             yield x
   ....:         else:
   ....:             yield -x
   ....:             

In [20]: sum(plusminus(xs))
Out[20]: 3

Which could also be expressed as:

sum(map(lambda x: operator.mul(*x), zip(xs, itertools.cycle([1, -1]))))

If you really want to use reduce, for some reason, you could do something like this:

class plusminus(object):
    def __init__(self):
        self._plus = True
    def __call__(self, a, b):
        self._plus ^= True
        if self._plus:
            return a+b
        return a-b

reduce(plusminus(), [2,5,8,10])  # output: -5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM