116k views
5 votes
. Write a function sumLastPart which, only using list library functions (no list comprehension), returns the sum of the last n numbers in the list, where n is the first argument to the function. (Assume that there are always at least n numbers in the list. For this problem and the others, assume that no error checking is necessary unless otherwise specified. But feel free to incorporoate error checking into your definition.) sumLastPart :: Int -> [Int] -> Int

User MEC
by
4.9k points

1 Answer

2 votes

Answer:

In Python:

def sumLastPart(n,thelist):

sumlast = 0

lent = len(thelist)

lastN = lent - n

for i in range(lastN,lent):

sumlast+=thelist[i]

return sumlast

Step-by-step explanation:

This defines the function

def sumLastPart(n,thelist):

This initializes the sum to 0

sumlast = 0

This calculates the length of the list

lent = len(thelist)

This calculates the index of the last n digit

lastN = lent - n

This iterates through the list and adds up the last N digits

for i in range(lastN,lent):

sumlast+=thelist[i]

This returns the calculated sum

return sumlast

User Goofology
by
4.8k points