Just zip the lists to generate pairs, multiply them and feed to sum:
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> sum(x * y for x, y in zip(a, b))
32
In above zip will return iterable of tuples containing one number from both lists:
>>> list(zip(a, b))
[(1, 4), (2, 5), (3, 6)]
Then generator expression is used to multiply the numbers together:
>>> list(x*y for x, y in list(zip(a, b)))
[4, 10, 18]
Finally sum is used to sum them together for final result:
>>> sum(x*y for x, y in list(zip(a, b)))
32
Answer from niemmi on Stack OverflowJust zip the lists to generate pairs, multiply them and feed to sum:
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> sum(x * y for x, y in zip(a, b))
32
In above zip will return iterable of tuples containing one number from both lists:
>>> list(zip(a, b))
[(1, 4), (2, 5), (3, 6)]
Then generator expression is used to multiply the numbers together:
>>> list(x*y for x, y in list(zip(a, b)))
[4, 10, 18]
Finally sum is used to sum them together for final result:
>>> sum(x*y for x, y in list(zip(a, b)))
32
You have some problems in your code, first off you cant index your list with parenthesis you need [], secondly you've created a generator not a number.
You need to zip your lists first:
In [3]: sum(i*j for i,j in zip(a, b))
Out[3]: 32
Or as a functional approach use operator.mul within map and sum:
In [11]: from operator import mul
In [12]: sum(map(mul, a, b))
Out[12]: 32
import operator
def sumproduct(*lists):
return sum(reduce(operator.mul, data) for data in zip(*lists))
for python 3
import operator
import functools
def sumproduct(*lists):
return sum(functools.reduce(operator.mul, data) for data in zip(*lists))
What about good old list comprehensions? (As mentioned by @Turksarama this only works for two lists)
sum([x * y for x, y in zip(*lists)])
Testing in Python 3.6:
In [532]: import random
In [534]: x = [random.randint(0,100) for _ in range(100)]
In [535]: y = [random.randint(0,100) for _ in range(100)]
In [536]: lists = x, y
Using list comprehensions
In [543]: %timeit(sum([x * y for x, y in zip(*lists)]))
8.73 µs ± 24.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Note that "tuple" comprehensions are slower
In [537]: %timeit(sum(x * y for x, y in zip(*lists)))
10.5 µs ± 170 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Using map
In [539]: %timeit(sum(map(lambda xi, yi: xi * yi, x, y)))
12.3 µs ± 144 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Using functools.reduce
In [542]: %timeit(sum(functools.reduce(operator.mul, data) for data in zip(*lists)))
38.6 µs ± 330 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
sympy - Produce the sum of products over two lists with python? - Stack Overflow
How do I sum product between a list and linear coefficient
Assignment 5-1 : Sum of Product - Make a function "sumProduct()" that receives two lists of integers and returns the sum of multiplying the corresponding list items Assumption: two lists must be the same length def sumproduct (11,12) : return sumP r result = sumproduct(list1, list2) main.py 1234 import random def sumoProduct (21,2): \# make your code
Sumproduct iteratively
Oh, so many problems in one post ;)
At first you should check if you can convert the list entries into integers. The best use case is to ask for forgivness and use try-except. That means if int(something) raises an Error, catch that specific error and handle it:
>>> def check_for_ints(entry):
try:
return int(entry)
except ValueError:
return None
>>> check_for_ints("2")
2
>>> check_for_ints("")
>>> check_for_ints("jhkajshkljh")
See, this will only return something that can converted to an integer.
Noe, we're taking your input lists and we're creating two new lists, with proper integers:
>>> list1 = ['10', '9', '', '20', '30', '1']
>>> list2 = ['15', '2', '', '58', '0', '2']
>>> inter1 = [check_for_ints(i) for i in list1 if not check_for_ints(i) is None]
>>> inter2 = [check_for_ints(i) for i in list2 if not check_for_ints(i) is None]
>>> inter1
[10, 9, 20, 30, 1]
>>> inter2
[15, 2, 58, 0, 2]
Now, we have interger lists, let us build a list of products:
>>> product = [i*j for i, j in zip(inter1, inter2)]
>>> product
[150, 18, 1160, 0, 2]
Finally we only have to sum it up:
>>> sum(product)
1330
Or without the intermediate steps:
>>> sum(i*j for i, j in zip(
(check_for_ints(i) for i in list1 if not check_for_ints(i) is None),
(check_for_ints(i) for i in list2 if not check_for_ints(i) is None))
)
1330
I used list comprehensions here, a powerful tool and shortcut, if you have problems understanding them, read this very nice piece of documentation. Good luck!
More on reddit.comIn [159]: import sympy as sy
In [160]: from sympy.abc import x
In [161]: terms = [1, x, x*(x-1)]
In [162]: coefficients = [-1,8.1,7]
In [163]: sum(t*c for t, c in zip(terms, coefficients))
Out[163]: 7*x*(x - 1) + 8.1*x - 1
Interestingly, sum(term*coef for term, coef in zip(terms, coefficients)) is a bit faster than sum(coef * term for coef, term in zip(coefficients, terms)):
In [182]: %timeit sum(term * coef for term, coef in zip(terms, coefficients))
10000 loops, best of 3: 34.1 µs per loop
In [183]: %timeit sum(coef * term for coef, term in zip(coefficients, terms))
10000 loops, best of 3: 38.7 µs per loop
The reason for this is because coef * term calls coef.__mul__(term) which then has to call term.__rmul__(coef) since ints do not know how to multiply with sympy Symbols. That extra function call makes coef * term slower than term * coef. (term * coef calls term.__mul__(coef) directly.)
Here are some more microbenchmarks:
In [178]: %timeit sum(IT.imap(op.mul, coefficients, terms))
10000 loops, best of 3: 38 µs per loop
In [186]: %timeit sum(IT.imap(op.mul, terms, coefficients))
10000 loops, best of 3: 32.8 µs per loop
In [179]: %timeit sum(map(op.mul, coefficients, terms))
10000 loops, best of 3: 38.5 µs per loop
In [188]: %timeit sum(map(op.mul, terms, coefficients))
10000 loops, best of 3: 33.3 µs per loop
Notice that the order of the terms and coefficients matters, but otherwise there is little time difference between these variants. For larger input, they also perform about the same:
In [203]: terms = [1, x, x*(x-1)] * 100000
In [204]: coefficients = [-1,8.1,7] * 100000
In [205]: %timeit sum(IT.imap(op.mul, terms, coefficients))
1 loops, best of 3: 3.63 s per loop
In [206]: %timeit sum(term * coef for term, coef in zip(terms, coefficients))
1 loops, best of 3: 3.63 s per loop
In [207]: %timeit sum(map(op.mul, terms, coefficients))
1 loops, best of 3: 3.48 s per loop
Also be aware that if you do not know (through profiling) that this operation is a critical bottleneck in your code, worrying about these slight differences is a waste of your time, since the time it takes to pre-optimize this stuff is far greater than the amount of time you save whilst the code is running. As they say, preoptimization is the root of all evil. I'm probably already guilty of that.
In Python2,
sum(IT.imap(op.mul, coefficients, terms))
uses the least memory.
In Python3, zip and map returns iterators, so
sum(t*c for t, c in zip(terms, coefficients))
sum(map(op.mul, coefficients, terms))
would also be memory-efficient.
Using a simple generator expression:
sum(coef * term for coef, term in zip(coefficients, terms))
Alternatively, instead of using zip you want to use something similar to zip_with:
def zip_with(operation, *iterables):
for elements in zip(*iterables):
yield operation(*elements)
And use it as:
import operator as op
sum(zip_with(op.mul, coefficients, terms))
As unutbu mentioned python already provide such a function in itertools.imap under python2 and the built'-in's map in python3, so you can avoid re-writing it and use either:
sum(itertools.imap(op.mul, coefficients, terms))
or
sum(map(op.mul, coefficients, terms) #python3
python 2 map works slightly differently when you pass more than one sequence and the length differ.
coefficient = [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 -3.20387018e-06]
How do I multiple each coefficient to the corresponding list of values [4, 3.2, 95, 3000], such that the answer is -0.009611610540000001
[4, 3.2, 95, 3000]*coeffient_a
I did just this but it is completely wrong.
was thinking of separating them by using split but because I'm importing linear regression from sklearn, .split is not possible
Hello!
I have two lists of numbers in "blocks" that I'd want to sumproduct.
list1 = ['10', '9', '', '20', '30', '1']
list2 = ['15', '2', '', '58', '0', '2']
By blocks I mean block 1 is the first 2 entries in the list and block 2 is the last 4 entries in the list. So the expected result is
#block1sumproduct = (10 * 15) + (9 * 2)
Block2 contains an empty value in index 2 so I'd have to skip that product and sum the rest:
Expected result:
#block2sumproduct = (20 * 58) + (30 * 0) + (1 * 2)
How can I do this iteratively like for i in range(len(list1[i]))?
What I've tried:
productlist = []
for i in range(len(list1)):
if list1[i] in ("", "N/A"):
productlist.append("")
pass
else:
productlist.append(int(list1[i]) * int(list2[i]))
However, the list doesnt know about the blocks and I don't know how to intuitively add it to the process. So when I go to sum the items in productlist I can do:
sumproductlist = {} #dictionary where the keys will be the blocks
sumproductlist[i] = productlist[i] + productlist[i+1] #where i is the number of blocks
But you see that I had to manually create the operation productlist[i] + productlist[i+1] so for the next block I'd need a new line to do productlist[i] + productlist[i+1] + productlist[i+2]which seems very unpythonic.
Oh, so many problems in one post ;)
At first you should check if you can convert the list entries into integers. The best use case is to ask for forgivness and use try-except. That means if int(something) raises an Error, catch that specific error and handle it:
>>> def check_for_ints(entry): try: return int(entry) except ValueError: return None>>> check_for_ints("2")2>>> check_for_ints("")>>> check_for_ints("jhkajshkljh")
See, this will only return something that can converted to an integer.
Noe, we're taking your input lists and we're creating two new lists, with proper integers:
>>> list1 = ['10', '9', '', '20', '30', '1']>>> list2 = ['15', '2', '', '58', '0', '2']>>> inter1 = [check_for_ints(i) for i in list1 if not check_for_ints(i) is None]>>> inter2 = [check_for_ints(i) for i in list2 if not check_for_ints(i) is None]>>> inter1[10, 9, 20, 30, 1]>>> inter2[15, 2, 58, 0, 2]
Now, we have interger lists, let us build a list of products:
>>> product = [i*j for i, j in zip(inter1, inter2)]>>> product[150, 18, 1160, 0, 2]
Finally we only have to sum it up:
>>> sum(product)1330
Or without the intermediate steps:
>>> sum(i*j for i, j in zip( (check_for_ints(i) for i in list1 if not check_for_ints(i) is None), (check_for_ints(i) for i in list2 if not check_for_ints(i) is None)) )1330
I used list comprehensions here, a powerful tool and shortcut, if you have problems understanding them, read this very nice piece of documentation. Good luck!
Hi! I'm working on a bot to reply with suggestions for common python problems. This might not be very helpful to fix your underlying issue, but here's what I noticed about your submission:
You are looping over an object using something like
for x in range(len(items)): foo(item[x])
This is simpler and less error prone written as
for item in items: foo(item)
If you DO need the indexes of the items, use the enumerate function like
for idx, item in enumerate(items): foo(idx, item)
Use numpy for a vectorised solution.
import numpy as np
A = 5
B = 7
y = np.array([1, 2, 3, 4, 5])
x = np.array([6, 7, 8, 9, 10])
# (y_i-A-B*x_i)^2
res = np.sum((y - A - B*x)**2)
A list-based solution is possible, but not recommended.
def calsum(n,list1,list2,A,B):
returnvalue=0
if n <= len(list1):
for i in range(n):
sumvalue=list2[i]-A-B*list1[i]
power=sumvalue ** 2
returnvalue += power
else:
print "Sum is not posible with given n value"
return returnvalue
list1=[1,2,3,4,5]
list2=[6,7,8,9,10]
if len(list1) == len(list2):
print"Length matched"
# calsum(n,list1,list2,A,B)
result=calsum(5,list1,list2,1,1)
print result
else:
print"Not in same length"