Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function to calculate sum?

This is what I've got and I'm not sure why it's not working

def sum(n):
    if (n>0):
        print (n)
        return sum(n)+sum(n-1)
    else:
        print("done doodly")

number = int(input(":  "))
sum(number)

For example if the use inputs 5, I want to program to calculate the sum of 5+4+3+2+1. What am I doing wrong ?

like image 236
kiasy Avatar asked Nov 13 '13 23:11

kiasy


2 Answers

Two things:

  • Calling sum(n) when computing sum for n won't do you much good because you'll recurse indefinitely. So the line return sum(n)+sum(n-1) is incorrect; it needs to be n plus the sum of the n - 1 other values. This also makes sense as that's what you want to compute.
  • You need to return a value for the base case and for the recursive case.

As such you can simplify your code to:

def sum(n):
    if n == 0:
        return 0
    return n + sum(n - 1)
like image 94
Simeon Visser Avatar answered Nov 15 '22 12:11

Simeon Visser


You forgot to return when n==0 (in your else)

>>> def Sum(n):
...   if not n:
...     return 0
...   else:
...     return n + Sum(n-1)
... 
>>> Sum(5)
15
like image 39
inspectorG4dget Avatar answered Nov 15 '22 12:11

inspectorG4dget