Write a function vector sum that has two arguments: vector1 and vector2 that are
ID: 3879566 • Letter: W
Question
Write a function vector sum that has two arguments: vector1 and vector2 that are lists of numbers. If vector1 and vector2 have different lengths, the function should return the null object None. Otherwise, the function should return a list of numbers that is equal to the sum of vector1 and vector2, considered as vectors.
So, vector sum([1,2,3], [4,5,6]) should return the list [5, 7, 9]. In general, if vector1 is the list [n0,n1,...,nk1] and vector2 is the list [m0, m1, . . . , mk1] then their sum, in this sense, is the list
[n0 +m0,n1 +m1,...,nk1 +mk1].
Your code should check to see if vector1 and vector2 have the same lengths. If not, then the function should return the null object None. This can be accomplished with the statement return None. Your code does not need to check that the arguments are lists of numbers. Do not confuse this vector addition with the python list extend method.
The code should be written in Python language.
Explanation / Answer
def vector_sum(vector1,vector2): #len() returns length of a list if len(vector1)!= len(vector2): #checking if length matches or not return None # returns None if length of two lists mismatch else: #if length of two lists matches #range(n) returns list of numbers from 0 to n vector3 = [vector1[i]+vector2[i] for i in range(len(vector2))] #adding elements present at same index in vector1 and vector2 return vector3 # print vector_sum([1,2,3],[4,5,6])
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.