Adding a difference of a pair of numbers in a list using map / reduce

I am doing exercises for functional programming concepts using python. I ran into this problem. I tried a lot and could not find a solution using functional programming constructors such as map / reduce, closures.

Problem: for a list of numbers

list = [10, 9, 8, 7, 6, 5, 4, 3]

Find the sum of the differences in each pair using Map / Reduce or any functional programming concepts like

[[10 -9] + [8 - 7] + [6 -5] + [4 - 3]] = 4

For me, the difficult part is highlighting pairs using map / reduce / recursion / clos

+4
source share
5 answers

The recursive relationship you are looking for is

f([4, 3, 2, 1]) = 4 - 3 + 2 - 1 = 4 - (3 - 2 + 1) = 4 - f([3, 2, 1])
+2

, , :

  • , , .

, : - , . map/reduce, , ! , " " , .

, :

pairs = [(10, 9), (8, 7), (6, 5), (4, 3)]

, , map, . :

  • , .
  • map .

, , , map reduce β„– 1.

+2

itertools.starmap:

l = [10, 9, 8, 7, 6, 5, 4, 3]

from operator import  sub
from itertools import starmap

print(sum(starmap(sub, zip(*[iter(l)] * 2))))
4

:

print(sum(map(lambda x: sub(*x), zip(*[iter(l)] * 2))))

:

from operator import itemgetter as itgt

print(sum(itgt(*range(0, len(l), 2))(l)) - sum(itgt(*range(1, len(l), 2))(l)))
+1

. ,

>>>import operator
>>>l=[10, 9, 8, 7, 6, 5, 4, 3]
>>>d= zip(l,l[1:])
>>>w=[d[i] for i in range(0,len(d),2)]#isolate pairs i.e. [(10, 9), (8, 7), (6, 5), (4, 3)]
>>>reduce(operator.add,[reduce(operator.sub,i) for i in w])
>>>4
0

.

l = [10, 9, 8, 7, 6, 5, 4, 3]
reduce(lambda x, y : y - x, l) * -1
0

Source: https://habr.com/ru/post/1617816/


All Articles