2

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

2
  • 1
    Post your code, since the sum(...) fragment is correct it must be that your splitting code is wrong. Commented Jun 7, 2009 at 6:58
  • 1
    what is your expected output? Commented Jun 7, 2009 at 8:58

4 Answers 4

8

You need:

>>> a = [1,2]
>>> b = [3,4]
>>> sum(i*j for i, j in zip(a,b))
11
Sign up to request clarification or add additional context in comments.

1 Comment

can't multiply sequence by non-int of type 'list'.. thats the error i am getting
3

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

Comments

1

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.