Addition with condition

Report a typo

When we add an array and a list together, the list is also treated as an array. However, we might not want the addition of a list and an array to yield the same result as the addition of two arrays.

Complete the custom_sum() function that takes two arguments. The two arguments can only be of the following types:

  1. Two NumPy arrays;

  2. A NumPy array and a list;

  3. Two lists.

In the first case, sum them and return the result. In the second case, return a string with the warning One argument is a list, and in the last case, return Both arguments are lists, not arrays.

All lists and arrays will be one-dimensional and of the same size. Note that you don't have to use any print() statements in this task.

Below is an example of the input and the expected outputs:

Input: [1, 2, 3], [4, 5, 6]
Expected Output: 'Both arguments are lists, not arrays'

Input: np.array([1, 2, 3]), [4, 5, 6]
Expected Output: 'One argument is a list'

Input: np.array([1, 2, 3]), np.array([4, 5, 6])
Expected Output: array([5, 7, 9])

Tip: You can check the variable type by calling isinstance(arg, type), which will return a boolean indicating whether the arg has the specified type. You can also use the type() for type checking as mentioned in the theory.

Write a program in Python 3
import numpy as np

one_list_warning = "One argument is a list"
two_lists_warning = "Both arguments are lists, not arrays"

def custom_sum(arg1, arg2):
...
___

Create a free account to access the full topic