1

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..

3
  • You won't be able to use reduce to solve this. How about a loop? Commented Feb 4, 2015 at 19:01
  • Do you want to understand how to use lambdas in Python or just how to write a function to compute x1-x2+x3-x4+x5-x6? Commented Feb 4, 2015 at 19:01
  • Computing a function Commented Feb 4, 2015 at 19:22

5 Answers 5

3

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

a = [2,5,8,10]
sum(a[::2])-sum(a[1::2])
-5
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

You can keep track of the position (and thus whether to do + or -) with enumerate, and you could use the fact that -12n is +1 and -12n+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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.