0

Hello there,

I've a homework assignment from a while ago that asks
"Implement a recursive Python function which returns the sum of the first n integers"

Now i just dont know exactly what it's asking and how to get started.

Recursive functions, right (my thoughts so far is it'll look something like )

def sum(n,amount):

and then i get stumped, i have worked with some so it usually continues with if (statement) == Integer etc.

But for this i seem to need to ask what the n integers are, then ask how many they want to add.

It's confused me, as my text wall probably has to you :P haha
Thanks for the help in advance, (try to keep it simple for me ^^)

3
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by thehivetyrant
Featured Replies
  • [code]def sum(n):[/code] Maybe that will help you get on track. If you have worked with other recursive functions, you will find that this will be very similar and should be only a few lines of code. Read More

  • 1

    Hint: Recursive functions call themselves, basically form a loop Your function definition should look like: def summer(n, mysum=0): You are summing from the top down. Each recursion you add n to mysum and decrease n by 1. So your recursive call becomes return summer(n-1, mysum+n) You loop until n drops … Read More

0

thinking about this more, should i define what the n numbers are and then just ask what the first amount of numbers to sum up are?

1
def sum(n):

Maybe that will help you get on track. If you have worked with other recursive functions, you will find that this will be very similar and should be only a few lines of code.

0

Just as a follow up in case this is your confusion:

sum(1) == 1 # 1
sum(2) == 3 # 1+2
...
sum(10) == 55 # 1+2+3+4+5+6+7+8+9+10
1

Hint:
Recursive functions call themselves, basically form a loop

Your function definition should look like:
def summer(n, mysum=0):

You are summing from the top down. Each recursion you add n to mysum and decrease n by 1. So your recursive call becomes
return summer(n-1, mysum+n)

You loop until n drops to zero, then you return mysum. That's where an if/else is used.

Your initial function call is something like
mysum = summer(5)
if you want to sum up integers 1 to 5.

0

I believe i understand now and i have completed the task,
I thank both of you for your help, both ways were extremely helpful,
just having it wrote down simply.

I am very grateful.

I also have to do an iterative version of this but i'm sure i'll be able to handle it now that i understand.

Again thanks to both of you.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.