Reputation: 36404
i have taken input in two different lists by splitting a line having integers 1 2
for eg 1 2
3 4
so now i have split it and kept it in lists , and want to multiply them like 1*3 +2*4, but when i try to do it , its giving me that it can only multiply integers and not lists !! help here
can't multiply sequence by non-int of type 'list'.. that's the error i am getting – when i do
c=sum(i*j for i, j in zip(a,b))
...
t=raw_input()
d =[]
for j in range(0,int(t)):
c=0
n=raw_input()
s = raw_input()
s1=raw_input()
a=[]
b=[]
a.append( [int(i) for i in s.split(' ')])
b.append([int(i) for i in s.split(' ')])
d.append(sum(i*j for i, j in zip(a,b)))
for i in d:
print i
that's my code
Upvotes: 2
Views: 7959
Reputation: 156188
You can do it in a pythonic way using sum, map and a lambda expression.
>>> a = [1,2]
>>> b = [3,4]
>>> prod = lambda a, b: a*b
>>> sum(map(prod, a, b))
11
the lambda a, b: a*b
bit also has a special name in python, operator.mul
>>> import operator
>>> sum(map(operator.mul, a, b))
11
Upvotes: 3
Reputation: 43130
Is this what you want?
t=raw_input()
d =[]
for j in range(0,int(t)):
#c=0
#n=raw_input()
s = raw_input()
s1 =raw_input()
a = [int(i) for i in s.split(' ')]
b = [int(i) for i in s1.split(' ')] # <--s1 not s
d.append(sum(i*j for i, j in zip(a,b)))
for i in d:
print i
Upvotes: 1
Reputation: 131600
It has nothing to do with multiplying integers, but you should probably be using the extend
method:
a.extend([int(i) for i in s.split(' ')])
b.extend([int(i) for i in s.split(' ')])
append
just tacks its argument on to the list as its last element. Since you are passing a list to append
, you wind up with a list of lists. extend
, however, takes the elements of the argument list and adds them to the end of the "source" list, which is what it seems like you mean to do.
(There are a bunch of other things you could do to fix up this code but that's probably a matter for a different question)
Upvotes: 0
Reputation: 101216
You need:
>>> a = [1,2]
>>> b = [3,4]
>>> sum(i*j for i, j in zip(a,b))
11
Upvotes: 8