Could this be written as a python reduction function?

Can you make it more pythonic using a map and / or reduce features? he simply sums up the products of each consecutive pair of numbers.

topo = (14,10,6,7,23,6)
result = 0
for i in range(len(topo)-1):
    result += topo[i]*topo[i+1]
+5
source share
7 answers

This is the nicest way I can think of:

import operator
sum(map(operator.mul, topo[:-1], topo[1:]))

Change . I just found a better way to do this:

import operator
import itertools

def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return a, b

def sum_products(l):
    return sum(itertools.imap(operator.mul, *pairwise(l)))

The credit for the pairwise function goes to the itertools documentation.

It is faster and uses less memory. Of course, this is less concise.

+9
source

You can use mapit reducelike this, but I'm not sure if it is more pythonic:

reduce( lambda x, y: x + y, map( lambda x, y: x * y, topo[:-1], topo[1:]) )

Most likely, this expression is sum + generator:

sum(topo[x] * topo[x+1] for x in xrange(len(topo)-1))
+6
source

:

mult = lambda (x, y): x * y
pairs = zip(list(topo), list(topo)[1:])
result = sum(map(mult, pairs))

, , .

+1

, , :

>>> topo = (14,10,6,7,23,6)
>>> sum((x*y for x,y in zip(topo[:-1],topo[1:])))
541
>>> 

>>> sum((topo[i]*topo[i+1] for i in range(len(topo)-1)))
541
+1

I would not call it pythonic, although it looks cooler, reduceit does not fit here:

def func(first, *rest):
    return reduce(lambda (x,y),z:(x+y*z,z), rest, (0,first))[0]

Please note that usage (x,y),zis 2.x.

0
source

With a decrease and Python <3.x:

from itertools import tee, izip

#recipe from http://docs.python.org/library/itertools.html#recipes
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

reduce(lambda s, (x, y):s + x * y, pairwise(topo), 0)

with card:

from operator import mul
from itertools import tee

a, b = tee(topo)
next(b, None)

sum(map(mul, a, b))
0
source

it can also get your answer

a= [14,10,6,7,23,6]
reduce(lambda a,b: a+b,  map(lambda (x,y): x*y, map(lambda i:(a[i],a[i+1]), range(len(a)-1))  ) )
0
source

All Articles