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.