Python Forum
Return the sum of the first n numbers in the list.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Return the sum of the first n numbers in the list.
#1
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)
Reply


Messages In This Thread
Return the sum of the first n numbers in the list. - by pav1983 - Jun-24-2020, 02:22 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Random Generator: From Word to Numbers, from Numbers to n possibles Words Yamiyozx 2 1,545 Jan-02-2023, 05:08 PM
Last Post: deanhystad
  How to sort a list with duplicates and return their unique indices. Echoroom 3 3,723 Sep-23-2022, 07:53 AM
Last Post: deanhystad
  Convert list of numbers to string of numbers kam_uk 5 3,149 Nov-21-2020, 03:10 PM
Last Post: deanhystad
  numbers in list - max value and average stewie 2 2,904 Apr-01-2020, 06:25 PM
Last Post: buran
  Question about Sorting a List with Negative and Positive Numbers Than999 2 12,950 Nov-14-2019, 02:44 AM
Last Post: jefsummers
  list of odd numbers cffiver2 2 5,290 Jul-12-2019, 09:46 AM
Last Post: perfringo
  Methods that return the highest score from the list erfanakbari1 7 7,383 Mar-26-2019, 08:32 PM
Last Post: aankrose
  Return not vowels list erfanakbari1 2 2,773 Mar-26-2019, 11:37 AM
Last Post: perfringo
  CODE for Bubble sorting an unsorted list of 5 numbers. SIJAN 1 2,347 Dec-19-2018, 06:22 PM
Last Post: ichabod801
  Regular Expressions in Files (find all phone numbers and credit card numbers) Amirsalar 2 4,201 Dec-05-2017, 09:48 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020