w3resource

Python Data Structures and Algorithms - Recursion: Calculate the harmonic sum

Python Recursion: Exercise-8 with Solution

Write a Python program to calculate the sum of harmonic series upto n terms.

Note: The harmonic sum is the sum of reciprocals of the positive integers.

Example:
harmonic series

Sample Solution:-

Python Code:

# Define a function named harmonic_sum that calculates the harmonic sum up to 'n' terms
def harmonic_sum(n):
    # Check if 'n' is less than 2 (base case for the harmonic sum)
    if n < 2:
        # If 'n' is less than 2, return 1 (base case value for the harmonic sum)
        return 1
    else:
        # If 'n' is greater than or equal to 2, calculate the reciprocal of 'n'
        # and add it to the result of recursively calling the harmonic_sum function with 'n - 1'
        return 1 / n + harmonic_sum(n - 1)

# Print the result of calling the harmonic_sum function with the input value 7
print(harmonic_sum(7))

# Print the result of calling the harmonic_sum function with the input value 4
print(harmonic_sum(4))

Sample Output:

2.5928571428571425                                                                                            
2.083333333333333 

Flowchart:

Flowchart: Recursion: Calculate the harmonic sum.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to calculate the sum of the positive integers of n+(n-2)+(n-4)... (until n-x =< 0).
Next: Write a Python program to calculate the geometric sum of n-1.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/data-structures-and-algorithms/python-recursion-exercise-8.php