0

Could someone help me with this. How do i make a recursive program that returns sum of 1**3 + 2**3 + ... + n**3?

4
Contributors
6
Replies
7
Views
8 Years
Discussion Span
Last Post by ZZucker
0

A recursive way

def sum_cubes(n):
    if n <= 0:
        if n < 0:
            raise ValueError
        else:
            return 0
    else:
        return n ** 3 + sum_cubes(n-1)

if __name__ == "__main__":
    print sum_cubes(10)

and a non recursive way

def sum_cubes2(n):
    if n < 0:
        raise ValueError
    res = 0
    while n:
        res += n ** 3
        n -= 1
    return res
0

Here is another way you can skin it:

def sum_cube(n, sum=0):
    if n > 0:
        x = n**3
        return sum_cube(n-1, sum+x)
    else:
        return sum

print sum_cube(5)  # 225
0

Here is another way you can skin it:

def sum_cube(n, sum=0):
    if n > 0:
        x = n**3
        return sum_cube(n-1, sum+x)
    else:
        return sum

print sum_cube(5)  # 225

This is a recursive way right?

0

Recursive means that the function calls itself, and it does so in line 4.
In Gribouillis's code it does so in line 8.

0

Here's another recursive way although it is kind of cheating:

>>> sum_cube = lambda N: eval(["0","(N*N*N) + sum_cube(N-1)"][N>0])
>>> sum_cube(10)
3025
This topic has been dead for over six months. 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.