Write a function named vectorSum(l1, l2)
that takes twolists of numbers and adds the numbers in l2 on l1, one by one.If l2 is shorter than l1, then l2 recycles from the beginningonce it is over. If l2 is longer than l1, then only the first partof l2 that matches the length of l1 is considered. Your functionmust return the summed up resulting list. For example,
vectorSum([1,2,3,4,5], [1,2,3]) returns [2,4,6,5,7] because:Write a function named `vectorSum(l1, l2)` that takes two
lists of numbers and adds the numbers in l2 on l1, one by one.
If l2 is shorter than l1, then l2 recycles from the beginning
once it is over. If l2 is longer than l1, then only the first part
of l2 that matches the length of l1 is considered. Your function
must return the summed up resulting list. For example,
vectorSum([1,2,3,4,5], [1,2,3]) returns [2,4,6,5,7] because:
1,2,3,4,5
+ + + + +
1,2,3,1,2 -> Here, l2 recycles from the beginning
= = = = =
2,4,6,5,7
vectorSum([1,2,3], [1,2,3,4,5]) returns [2,4,6] because:
1,2,3
+ + +
1,2,3,4,5 -> Here, only the first 3 items of l2 are used
= = =
2,4,6
vectorSum([1,2,3,4,5], [1,2,1,2,1]) returns [2,4,4,6,6]
1,2,3,4,5
You can assume that l1 and l2 are not empty.
vectorSum([1,2,3,4,5], [1,2,3]) returns [2,4,6,5,7] because:
1,2,3,4,5
+
+
+
+
+
1,2,3,1,2 -> Here, l2 recycles from the beginning = = = = = 2,4,6,5,7
vectorSum([1,2,3], [1,2,3,4,5]) returns [2,4,6] because:
1,2,3
+
+
+
1,2,3,4,5 -> Here, only the first 3 items of l2 are used = = = 2,4,6
vectorSum([1,2,3,4,5], [1,2,1,2,1]) returns [2,4,4,6,6] because:
1,2,3,4,5
+
+
+
+
+
1,2,1,2,1 -> Here, length of l2 matches the length of l1 = = = = = 2,4,4,6,6
Using a list comprehension to iterate over the length of the first list, and using the remainder of the length of the first list divided by the length of the second list as the index for the second list, providing us effectively with a loop over the second list if that list is shorter than the first list.
len(l1) > len(l2)
>>> l1 = [1,2,3,4,5]
>>> l2 = [1,2,3]
>>> [l1[i] + l2[i%len(l2)] for i in range(len(l1))]
[2, 4, 6, 5, 7]
len(l1) < len(l2)
>>> l1 = [1,2,3]
>>> l2 = [1,2,3,4,5]
>>> [l1[i] + l2[i%len(l2)] for i in range(len(l1))]
[2, 4, 6]
len(l1) == len(l2)
>>> l1 = [1,2,3,4,5]
>>> l2 = [1,2,1,2,1]
>>> [l1[i] + l2[i%len(l2)] for i in range(len(l1))]
[2, 4, 4, 6, 6]