Make a function called soma_h to compute and return the value H with N terms where N is integer and given with input

Asked

Viewed 74 times

2

I made the code but I don’t know why the output is 1.

def soma_h(n):
    soma = 0
    for i in range(1, n+1):
        soma = soma + float(1//i)
    return round(soma, 2)

Note: H = 1 + 1/2 + 1/3 ... + 1/n

  • 1

    The // operator (floor Division or entire division) will always give zero for any denominator greater than 1. I think it would be enough to do: soma += 1/i

  • try to define this way: soma = 0,0 for the value not to be treated as integer

  • 1

    It worked. The problem was // even

1 answer

2


What you need is to implement a function to calculate the sum of the inverses of the first positive INTEGERS.

def soma_h(n):
    soma = 0
    for c in range(1, n + 1):
        inverso = (1/c)
        soma += inverso
    return round(soma, 2)


num = int(input('Digite um número: '))

print(soma_h(num))

Note that when we execute the code we are passed the following message: Digite um número: . Right now we must enter an integer number and press enter. From this moment the code will calculate the summation of inverse of 1 until n.

Testing the code:

If we want to calculate the sum of inverse of the first integers n we would have:

n = 2 = (1/1) + (1/2) = 1.50
n = 3 = (1/1) + (1/2) + (1/3) = 1.83
n = 4 = (1/1) + (1/2) + (1/3) + (1/4) = 2.08

Another interesting way to resolve this issue by List Comprehensio would be:

def soma_h(n):
    return round(sum([(1/x) for x in range(1, n + 1)]), 2)


num = int(input('Digite um número: '))

print(soma_h(num))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.