【问题标题】:for loop in python with square root condition checkin带有平方根条件检查的python中的for循环
【发布时间】:2021-05-23 17:57:13
【问题描述】:

在 C 中,我们可以使用这个 for 循环检查值“i”是否小于 n 的平方根

for (int i = 2; i * i <= n; i++)

我用while循环为:

i = 2
while(i * i <= n):
    i+=1

我们可以在python中使用for循环吗?

【问题讨论】:

  • 为什么不呢? @D_Raja
  • 那怎么检查呢? @Vishnudev

标签: python-3.x loops for-loop


【解决方案1】:

其实差不多。

在python中,典型的for循环使用range(start, end, step)函数来获取索引变量i。它循环通过i=starti=end-1,同时将i 递增step

for i in range(start, end, step):

这相当于C/C++/Java的

for (int i = start; i < end; i+=step)

然后,停止n 的平方根。您只需使用以下内容:

import math
for i in range(2, int((math.sqrt(n))+1):

注意math.sqrt(n) 给出了float。然后将其包装在int 中,采用floatfloor。并且由于for 循环在end-1 处停止,我们加1,因此这模仿了OP 请求的行为,即i*i &lt;= n

一些例子使这更容易: 例如n=4,然后:

  • math.sqrt(n)=2.0,
  • int((math.sqrt(n))=2,
  • int((math.sqrt(n))+1=3
    for i in range(2, 3) 将使用 i=2 运行循环,并在 i 达到 3 之前停止。

现在,如果 n 不是完美的正方形: 例如n=10,

  • math.sqrt(n)=3.16...
  • int((math.sqrt(n))=3,
  • int((math.sqrt(n))+1=4
    for i in range(2, 4) 将使用i=2i=3 运行循环,并在i 达到4 之前停止。

虽然循环是完全一样的。 i*i 的另一种写法是 python 中的i**2

i=2
while i**2 <= n:
    i+=1

【讨论】:

    【解决方案2】:

    @Tim 提到它是可能的,因为在 python 中 for 循环实际上遍历了一系列值,但在 C/C++ 中,我们拥有的是 initialization;condition;increment,因此在 python 中不遵循确切的结构,而是它的 for x in range()所以确切的语法代码是不可能的,但您可以实现相同的功能(也可以使用 while 循环或 for 循环,如图所示),因为它基于语言提供的功能!

    希望它能给你答案!

    【讨论】:

      猜你喜欢
      • 2022-10-31
      • 2021-07-06
      • 1970-01-01
      • 2014-09-12
      • 1970-01-01
      • 2019-06-04
      • 2017-07-11
      • 2014-08-30
      • 2013-03-27
      相关资源
      最近更新 更多