[英]It doesn't append as floating Python | Problem #18
I'm writing this code for the problem #18 in Codeabbey.我正在为 Codeabbey 中的问题 #18编写此代码。 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.我需要计算数字数组[150, 0, 5, 1 10, 3]
平方根我必须将此数组划分为三个数组 (x,n) [[150, 0], [5, 1], [10 3]]
其中 x: 是我要计算其平方根的数字,n: 是我必须尝试公式 r = (r + x / r) / 2 以获得结果的次数是 r,r 从 1 开始。没有问题,问题是当我必须附加结果时,因为如果 r 是3.0
我必须将其附加为整数: 3
但如果 r 是3.964
我必须附加它作为浮动。
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():如果我不使用 is_integer(),这就是我得到的结果:
'1 3.0 3.196xxxxx'
What the output should be:输出应该是什么:
1 3 3.196
I can't see where the problem is.我看不出问题出在哪里。
is_integer
is a method you run on float
type. is_integer
是一种在float
类型上运行的方法。 You forgot to invoke it, so it evaluates to True
as it returns a builtin which is something (not nothing).你忘记调用它,所以它评估为True
因为它返回一个内置的东西(不是什么)。
Just replace只需更换
if r.is_integer:
with和
if r.is_integer():
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.