[英]How do I simplify this Python for loop?
I'm relatively new to Python and I was wondering how I could simplify the following code any further.我对 Python 比较陌生,我想知道如何进一步简化以下代码。 The code determines whether a number, n
, is a power of 2
by using a for loop
.该代码使用for loop
确定数字n
是否为2
的幂。
def is_power(n):
if n <= 2:
return True
for i in range(3, n):
if i * i == n:
return True
return False
Here is an oversimplification :)这是一个过度简化:)
def is_power_of_two(n):
return n and not (n & (n - 1))
You could achieve it by checking if the root square is an integer value :您可以通过检查平方根是否为整数值来实现它:
def is_power(n):
return True if n**(1/2) == int(n**(1/2)) else False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.