tags:

views:

1097

answers:

4

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

+4  A: 

You need:

>>> a = [1,2]
>>> b = [3,4]
>>> sum(i*j for i, j in zip(a,b))
11
sykora
can't multiply sequence by non-int of type 'list'.. thats the error i am getting
mekasperasky
A: 

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
TokenMacGuy
map and lambda are "pythonic way"?
SilentGhost
A: 

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)

David Zaslavsky
+1  A: 

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
Nick D