【问题标题】:My function for checking perfect squares does not work, but its components work individually我检查完美正方形的功能不起作用,但它的组件可以单独工作
【发布时间】:2021-06-24 09:40:25
【问题描述】:

这是我的功能。

def is_square(n):    
    x = n ** 0.5
    return((x >= 0) & (x % 1 == 0))

当我跑步时

is_square(-1)

我收到此错误消息:

Traceback (most recent call last):

  File "<ipython-input-183-33fbc4575bf6>", line 1, in <module>
    is_square(-1)

  File "<ipython-input-182-32cb3317a5d3>", line 3, in is_square
    return((x >= 0) & (x % 1 == 0))

TypeError: '>=' not supported between instances of 'complex' and 'int'

但是,此功能的各个组件都可以完美运行。

x = -1 ** 0.5

x >= 0
Out[185]: False

x % 1 == 0
Out[186]: True

(x >= 0) & (x % 1 == 0)
Out[189]: False

为什么我的功能不起作用?

【问题讨论】:

  • 这不等同。在你的程序中是(-1) ** 0.5,而不是-1 ** 0.5(-1)**0.5 是一个复数,支持与实数不同的运算。
  • -1求平方根,你认为应该是什么结果?当您将其与 0 进行比较时,您期望会发生什么?错误信息写在not supported between instances of 'complex' and 'int'的地方,你真的明白'complex'在这里是什么意思吗?看起来你实际上可能有一个数学理论问题,而不是一个编程问题。
  • 明白 - 谢谢!

标签: python function integer boolean complex-numbers


【解决方案1】:

您在函数中所做的是将 x 定义为 sqrt(n)。 对于n = -1,这意味着x = i(意味着sqrt(-1))所以&gt;= 表达式没有真正的意义。 当您单独测试该部分功能时,代码被读取为-(1**0.5)。 您会发现,当您将其重写为 (-1)**(0.5) 时,它将不再起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多