Could someone help me with this. How do i make a recursive program that returns sum of 1**3 + 2**3 + ... + n**3?
doeman
0
Newbie Poster
Recommended Answers
Jump to PostA 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 …
Jump to PostHere 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
All 6 Replies
Gribouillis
1,391
Programming Explorer
Team Colleague
ZZucker
342
Practically a Master Poster
doeman
0
Newbie Poster
ZZucker
342
Practically a Master Poster
BearofNH
104
Posting Whiz
ZZucker
342
Practically a Master Poster
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.