Skip to content
Advertisement

It doesn’t append as floating Python | Problem #18

I’m writing this code for the problem #18 in Codeabbey. I need to calculate the square root of an array of numbers [150, 0, 5, 1 10, 3] I have to divide this array in three arrays (x,n) [[150, 0], [5, 1], [10 3]] where x: is the number I want to calculate the square root of and n: is the number of times I have to try the formula r = (r + x / r) / 2 to get the result which is r, r is starting with 1. There’s no problem with that, the problem is when I have to append the result because if r is 3.0 I have to append it as an integer: 3 but if r is 3.964 I have to append it as a floating.

def squareRoot():
    rawArr = [int(n) for n in input().split()]
    arr = [rawArr[i:i+2] for i in range(0,len(rawArr)-1,2)]
    results = []

    for a in arr:
        x,n = a
        r = 1.0
        for i in range(0,n):
            r = (r + x / r) / 2
        if r.is_integer:
            results.append(str(int(r)))
        else:
            results.append(str(round(r,3)))
    return " ".join(results)

The input is:

150 0 5 1 10 3

and the output is:

'1 3 3'

This is what I get if I don’t use is_integer():

'1 3.0 3.196xxxxx'

What the output should be:

1 3 3.196

I can’t see where the problem is.

Advertisement

Answer

is_integer is a method you run on float type. You forgot to invoke it, so it evaluates to True as it returns a builtin which is something (not nothing).

Just replace

        if r.is_integer:

with

        if r.is_integer():
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement