Python Forum
Return the sum of the first n numbers in the list. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Return the sum of the first n numbers in the list. (/thread-27841.html)



Return the sum of the first n numbers in the list. - pav1983 - Jun-24-2020

Hi, I am stuck on this one. It makes no sense to me. I did attempt, but I'm having no luck. I think it comes down to knowing how to get the first n numbers of the list. Below is my code so far. If I am just not understanding what this is asking, please let me know and guide me a little bit here. I know I am fairly close to getting the answer on my own.

Given a list and an integer n, return the sum of the first n numbers in the list.

Examples
sum_first_n_nums([1, 3, 2], 2) ➞ 4

sum_first_n_nums([4, 2, 5, 7], 4) ➞ 18

sum_first_n_nums([3, 6, 2], 0) ➞ 0
Notes
If n is larger than the length of the list, return the sum of the whole list.


def sum_first_n_nums(lst, n):
	if n <= len(lst):
		return n * (n + 1) / 2
	elif n > len(lst):
		return sum(lst)
def sum_first_n_nums(lst, n):
	if n <= len(lst):
		return lst[n:]
	elif n > len(lst):
		return sum(lst)



RE: Return the sum of the first n numbers in the list. - pyzyx3qwerty - Jun-24-2020

If list1's length is greater, you could store numbers under a variable like
nums = list1[0:]
If it's smaller, define the variable as
nums = list1[0:n]
Then, in the end, call the sum of nums like
return sum(nums)
It will give expected output


RE: Return the sum of the first n numbers in the list. - pav1983 - Jun-24-2020

Thanks for you help, but I figured it out without setting the variables. I forgot it was the sum of the first n numbers.

def sum_first_n_nums(lst, n):
	if n <= len(lst):
		return sum(lst[0:n])
	elif n > len(lst):
		return sum(lst)



RE: Return the sum of the first n numbers in the list. - deanhystad - Jun-24-2020

If lst has less elements than n, sum returns the sum of the entire list.
def sum_first_n_nums(lst, n):
    return sum(lst[:n])
And since sum fixes things automatically there isn't any reason to write you own function.