0

I'm trying to write a program that takes in two lists and returns a single list that is an element-by-element multiplication of the two arguments in each of the lists.
If the lists are different lengths,it should return a list that is as long as the shorter of the two. Here's what I've written:

s = raw_input("Enter the first list:")
c = list(s)
c = s.split()
c = map(int, c)

t = raw_input("Enter the second list:")
d = list(t)
d = s.split()
d = map(int, d)

def multiply(c, d):
    cd = [ ]
    for i in range(0, len(c)):
    cd.append(c[i]*d[i])

The general idea is that the user inputs numbers, which is converted into an integer list. However, there are errors with not being able to multiple strings with integers and "invalid literal for int() with base 10." I've been working on this for 2 hours now and I can't figure out what to do!!! Please help!

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
Jane
  • 1
  • 1
  • 4

6 Answers6

3

You can try mapping with multiplication operator!

>>> from operator import mul
>>> map(mul,c,d)

Example!

>>> from operator import mul
>>> c
[1, 2, 3]
>>> d
[1, 2, 3]
>>> map(mul,c,d)
[1, 4, 9]

Hope this helps!

Keerthana Prabhakaran
  • 3,766
  • 1
  • 13
  • 23
1

I think there're some spelling mistakes with your code.It should like this:

s = raw_input("Enter the first list:")
c = s.split()
c = map(int, c)

t = raw_input("Enter the second list:")
d = t.split()
d = map(int, d)

#if you want align two lists,try this:
if len(d)<len(c):
    d.extend([1]*(len(c)-len(d)))
elif len(d)>len(c):
    c.extend([1] * (len(d) - len(c)))
else:
    pass
#you will get c [2,3,1,1,1]  d[4,5,2,6,7]

cd = []
def multiply(c, d):
    for i in range(0, len(c)):
        cd.append(c[i]*d[i])

multiply(c, d)

print cd

Or you can try this:

lista=raw_input("list a")

listb=raw_input("list b")


print [a*b for a,b in zip(map(int,lista.split()),map(int,listb.split()))]
McGrady
  • 10,869
  • 13
  • 47
  • 69
  • Thanks a lot, it worked! However, I have to use a definition statement in the code. I added one in before the print statement (defMultiple(a,b):) but it keeps on saying a and b aren't defined. I set them = to list and listb respectively, but that didn't work. Any idea on how to fix this? Thanks again! – Jane Mar 03 '17 at 05:46
  • @Jane you should match the function arguments when you call your function. Call it like; `multiply(a,b)`. And those variables will be sent into function scope. – umutto Mar 03 '17 at 05:53
  • @Jane Please check out your code and function arguments,you can try to use IDE(like Pycharm) help you debug code.And if this issue is fixed,please accept the answer. – McGrady Mar 03 '17 at 05:54
  • Thanks again. I've studied your first one since it makes more sense to me. I also tested it out- it only seems to work with lists of the same length. Any idea on how to change that? – Jane Mar 03 '17 at 06:02
  • Hey, turns out your old one did work, but the problem was I changed some of the variables (I was supposed to use different letters) and for some reason the code ceased to work when I did that. I've been it over it a ton of times, and I have very carefully changed each one respectively. Any idea why this error might be occurring? – Jane Mar 03 '17 at 06:25
  • @Jane Check out your code carefully,by the way,you should develop good habits of using variables,see more details from [Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/). – McGrady Mar 03 '17 at 06:32
  • I've examined it again, and it turns out the problem is that certain numbers just don't work. I don't understand why; for example, if I type in 1 4 3 1 for the first sequence and 3 2 3 for the second it works, but if I type in 1 2 3 4 and then 1 2 3 it's "out of range." I don't understand why... – Jane Mar 03 '17 at 06:37
  • @Jane My code works well.I suppose you should ask another question. – McGrady Mar 03 '17 at 06:41
0

You could use list comprehension mixed with zip as mentioned in this post. Refer this link link.

Community
  • 1
  • 1
0

Lets work on your code a bit so its easier to understand. You were accidentally giving wrong inputs etc..;

s = raw_input("Enter the first list:")
c = s.split()
c = list(map(int, c))

t = raw_input("Enter the second list:")
d = t.split()
d = list(map(int, d))

def multiply(c, d):
    cd = [ ]
    for i in range(0, len(c)):
        cd.append(c[i]*d[i])
    return cd

print multiply(c, d)

But of course you can do it in one line or more pythonic way using list comprehension like other answers said.

umutto
  • 7,460
  • 4
  • 43
  • 53
  • why you say we can't do it in one liner!? – Keerthana Prabhakaran Mar 03 '17 at 06:01
  • Thanks! For some reason, when I change the variables it ceases to work. Any idea why this might be? – Jane Mar 03 '17 at 06:24
  • @KeerthanaPrabhakaran no I said you can do it in one line, but my answer was just to fix OP's errors, not to implement a new one liner solution. @Jane you should be consistent with your variables, your function `multiply(list1,list2)` takes 2 lists, you should call it with two lists that you want to get multiplied. – umutto Mar 03 '17 at 06:36
0

Let's take this a step at a time.

First, we know that we need to read in two list of numbers from the user. For the sake of simplicity, let us assume that the user can entire a list of numbers by entering one or more space-sperated values. eg.

1 2 3 4 5

Now that we have defined how our input is going to be entered, we can properly parse it. To do so, we will first split the input into a list of strings using .split(), and then convert each string to an actual number using a list comprehension. But since we'll have to use this logic two times, lets encapsulate it in a function called get_numbers():

def get_numbers():
    numbers = input("Enter some numbers: ").split()
    return [int(n) for n in numbers]

Now we can use our new function to gather two lists of numbers from the user. I'll name the first list list1 and the second list2:

list1 = get_numbers()
list2 = get_numbers()

Now that we've solved the problem of getting the user input into lists, we can turn our attention to the second part of the problem:

return[ing] a single list that is an element-by-element multiplication of the two arguments in each of the lists. If the lists are different lengths, it should return a list that is as long as the shorter of the two.

Let's start off by just fulfilling the first requirement, then we'll later handle the second.

We know that we need to grab each element n-th element from the two list in pairs, multiple them together, and put the result in a new a list. To accomplish the task of iterating over the list in pairs, we can use zip(). Again, we'll use a list comprehension instead of a regular for loop:

[a*b for a, b in zip(list1, list2)]

Now let's also wrap the in a function for connivence, and call it zip_and_multiply():

def zip_and_multiply(list1, list2):
    return [a*b for a, b in zip(list1, list2)]

However, without realizing it, we've also fulfilled our second requirement("If the lists are different lengths, it should return a list that is as long as the shorter of the two.").

You see, if zip() is given two lists of different lengths, it stops zipping at the end of the shortest of the two lists, thus, it perfectly fulfills the second requirement.

All that's left to do is to print the result of zip_and_multiply() used on list1 and list2(the variables):

print zip_and_multiply(list1, list2)

After writing all of the above code(phew!), our final program in totality would be(Note this is in a different order than how the code appeared above):

def get_numbers():
    numbers = input("Enter some numbers: ").split()
    return [int(n) for n in numbers]

def zip_and_multiply(list1, list2):
        return [a*b for a, b in zip(list1, list2)]

list1 = get_numbers()
list2 = get_numbers()

print zip_and_multiply(list1, list2)

One should note however, the above code is missing many sections of code which are normally in said programs, such as proper error handling.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
0

Firstly, List Comprehension is all you need for your problem. Now lets breakdown your problem -

Get input from user - for the

"errors with not being able to multiple strings with integers"

problem, assuming that you are working on integer values, you need to make sure that all the values in the lists are of type int. You can make the user enter the values and map it to int type making use -

user_input = map(int, raw_input("Enter the first list:").strip().split(' '))

This will take space separated integers from users and convert them to a list.

Now for

"invalid literal for int() with base 10."

you need to make sure that only integers are being entered while taking the input from the user. In case user provide a string or an empty response it will throw this error.

Multiply two Lists - While multiplying yours list following scenarios can arise :

1.Both lists are of same length.

2.Both lists are of unequal length.

You need to check the length of lists and if length differ then multiply the elements form both lists until the elements from smaller list are exhausted and append the remaining elements from larger list. Below is the code snippet for your problem statement -

c = map(int, raw_input('Enter First List').strip().split(' '))
d = map(int, raw_input('Enter Second List').strip().split(' '))

answer = [c[i]*d[i] if i<min(len(c), len(d)) else (c[i] if \
len(c)>len(d) else d[i]) for i in xrange(max(len(c), len(d)))]

answer will contain the desired result set.