Click here to Skip to main content
15,902,939 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Compulsory Task 1
Follow these steps:
● In a file called sum_recursion, create:
o a function that takes a list of integers and an integer as 2
arguments. The integer will represent an index point.
o This function needs to add the sum of all the numbers in the list
up until and including the given index point by making use of
recursion and no loops.
Examples of input and output:
adding_up_to([1, 4, 5, 3, 12, 16], 4)
=> 25

What I have tried:

<pre>def sumoflist(list):
    if len(list) == 1:
        return list[0]
    else:
        return list[0] + sumoflist(list[1:])


list = [5,2,3,1]
sum = sumoflist(list)
print(sum)
Posted
Updated 23-Jul-22 18:36pm
Comments
Richard MacCutchan 24-Jul-22 3:19am    
"a function that takes a list of integers and an integer as 2
arguments. The integer will represent an index point."

Your function accepts only one argument.
def sumoflist(list, index):
Thandeka Zulu 24-Jul-22 15:31pm    
I do know that part. I need some assistance on how will I utilise the index inside the function.

1 solution

See here: Python Functions[^]
It explains the process and gives examples!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900