披露:此问题来自codewars。
编写一个方法,如果给定参数为4的幂,则返回true,否则返回false。如果parameter不是Integer(例如String,Array),则方法也应返回false。
我无法为自己的一生弄清楚我所缺少的优势。对于某些测试,两个代码示例均产生相同的错误,即“ True应该等于False”。 (当第一种方法不起作用时,我尝试了两种方法,因为我肯定第二种方法可以。)
def powerof4(n):
if n <= 0 or not isinstance(n, int): return False
else:
while (n != 1):
if (n%4 != 0): return False
else: n = n/4
return True
和
import math
def powerof4(n):
if ((not isinstance(n, int)) or n&(n-1) != 0 or n == 0):
return False
#Now, I cheat, since 4^n = (2^n)^2
reduce_to_2 = math.sqrt(n)
if math.floor(reduce_to_2) != reduce_to_2:
return False
else:
reduce_to_2 = int(reduce_to_2)
return reduce_to_2&(reduce_to_2 - 1) == 0
python大神给出的解决方案
您的第一个问题是,您要检查参数的类型是否为int
,但要从大于2 ^ 32的数字开始,对于codewars使用的Python 2而言,这不是正确的。
下一个错误是,如果您在测试失败的代码战中打印该值,则会看到它是针对调用powerof4(True)
的。 isinstance(True, (int,long))
是True
,因为bool是int
的子类。
在您的第一个代码中,将typecheck更改为
if n <= 0 or type(n) not in (int,long): return False
为该问题添加另一个变体。一段时间前,当我最初解决此问题时,我有点摆弄了:)
def powerof4(n):
if type(n) not in (int, long):
return False
bin_repr = bin(n)[2:]
return bin_repr[0]=="1" and bin_repr.count("0")%2==0 and bin_repr.count("1")==1