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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With