Python-检查数字是否为正方形 [英] Python - Check if a number is a square

查看:55
本文介绍了Python-检查数字是否为正方形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个函数,该函数返回数字输入是否为正方形

I wrote a function that returns whether a number input is a square or not

def is_square(n):
    if n<1:
        return False
    else:
        for i in range(int(n/2)+1):
            if (i*i)==n:
                return True
            else:
                return False

我相信此代码可以正常工作.但是当我做测试用例时,例如: test.expect(is_square(4)),它表示该值不是预期的值.

I am confident that this code works. But when I did the test cases, example:test.expect( is_square( 4)), it says that the value is not what was expected.

推荐答案

您的函数实际上不起作用,因为它将立即在找到的第一个非平方根上返回False.相反,您将需要将代码修改为:

Your function doesn't actually work, as it will immediatley return False on the first non-square-root found. Instead you will want to modify your code to be:

def is_square(n):
    if n<1:
        return False
    else:
        for i in range(int(n/2)+1):
            if (i*i)==n:
                return True
        return False

,以便仅在检查了所有可能的平方根后才返回false.您可能还需要研究 math.sqrt() float.is_integer().使用这些方法,您的功能将变为:

such that it only returns false once all possible square roots have been checked. You may also want to look into math.sqrt() and float.is_integer(). Using these methods your function would become this:

from math import sqrt

def is_square(n):
    return sqrt(n).is_integer()

请记住,此方法不适用于非常大的数字,但是您的方法使用它们的速度将非常慢,因此您必须选择要使用的方法.希望我能帮上忙!

Keep in mind that this method will not work with very large numbers, but your method will be very slow with them, so you will have to choose which to use. Hope I helped!

这篇关于Python-检查数字是否为正方形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆