191k views
25 votes
Write a function sum_of_ends that takes a list of numbers as an input parameter and: if the list is empty, returns 0 if the list is not empty, returns the sum of the first element (at index 0) and the last element (at index length - 1) Note that for a list with only one element, the first element and the last element would be the same one element in the list and thus the function should return the sum of the element with itself. ex: If a

User Yogev
by
4.3k points

1 Answer

7 votes

Answer:

Step-by-step explanation:

The following code is written in Python. It creates the function called sum_of_ends and does exactly as the question asks, it sums the first and last elements of the array and returns it to the user, if the array is empty it will return 0.

def sum_of_ends(num_arr):

if len(num_arr) == 0:

return 0

else:

sum = num_arr[0] + num_arr[-1]

return sum

User Eyn
by
4.0k points