Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this be written as a python reduce function?

Tags:

python

Can you make this more pythonic by using the map and/or reduce functions? it just sums the products of every 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]
like image 272
Nathan Avatar asked May 08 '11 00:05

Nathan


1 Answers

This is the nicest way I can think of:

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

Edit: I've just found out there's 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)))

Credit for pairwise function goes to the itertools documentation.

This is faster and uses less memory. Of course, it's less concise.

like image 126
Nick ODell Avatar answered Sep 20 '22 12:09

Nick ODell