TransWikia.com

a (recursive) function that will calculate sum for a given n

Stack Overflow Asked by randomobject123 on January 17, 2021

How to write a recursive function that will calculate this sum for a given n?

 n
 ∑  1/k
k=1

My code:

def sum(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return sum(1/n) + sum(1/n+1)

print(sum(3))

For n = 3 the output should be: 1.8333333333333333

2 Answers

You should avoid declaring a new function with the name sum as there already exists a built-in function with this name.

You can recursively calculate

 n                              n-1
 ∑  1/k         ==         1/n + ∑  1/k
k=1         for n > 0           k=1

with

def my_recursive_sum(n):
    if n <= 0:
        return 0
    if n == 1:
        return 1
    return 1/n + my_recursive_sum(n-1)

print(my_recursive_sum(3))

Correct answer by Thomas Sablik on January 17, 2021

Your solution would easily reach the maximum recursion limit.

when you call again the function using 1/n and 1/n+1 you would use the same n and increase it, so you would never reach the end condition. the next couple of sum would never have an n value equal to 0 or 1.

Also you should not call again the function with 1/n otherwise you would endup looping forever in the function recall

you should use something like:

>>> def my_sum(n):
...     if n < 1:
...             return 0
...     return 1/n + my_sum(n-1)
... 
>>> print(my_sum(3))
1.8333333333333333
>>> 11/6
1.8333333333333333
>>>

edit: Like mentioned in another answer you should avoid using sum as a name of a function because it's a name already use by python

Answered by tia.milani on January 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP