Home > Mobile >  How do I get the negative of this answer? Why can I not just put a negative sign when returning the
How do I get the negative of this answer? Why can I not just put a negative sign when returning the

Time:11-18

The problem

The problem is basically using if and else loops to get the outputs as shown above. So based on the formula for harmonic series, I returned the following results should n be above 1

My code was basically this and seems to have gotten the right answers but I always end up with a negative value. Is there something wrong with the logic or is there a way to get the reverse of the results because I have tried doing min() and subtracting from 0.

def alternating(n):
    if n == 1:
        return 1
    else:
        return 1/n   (-1**(n % 2)) * alternating(n-1)

CodePudding user response:

Your function is not correct.

This one is:

"""
Harmonic series using recursion

See https://stackoverflow.com/questions/74476333/how-do-i-get-the-negative-of-this-answer-why-can-i-not-just-put-a-negative-sign
See https://i.stack.imgur.com/ShNUi.png
"""


def alternating(k):
    if k != 1:
        return (-1) ** (k   1) / k   alternating(k - 1)
    else:
        return 1

Please learn to stop saying and writing "basically". It's a high-tech filler word, akin to "um". Don't use it.

  • Related