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

Recommended Answers

All 6 Replies

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

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

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?

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

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

Wow BearofNH, the Auberge Pyrenees-Cevennes of Python.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.