python3 函数使用 while 循环检查参数是否为 2 的幂,并且不使用数学函数

问题描述 投票:0回答:3

学习python3中的函数。课程问题是使用 while 循环(并且不使用数学函数)定义一个函数,该函数确定参数是否为 2 的幂。如果是,则返回 True。如果不是,则返回 False。这是起始代码:

def is_power_of_two(n):
  # Check if the number can be divided by two without a remainder
  while n % 2 == 0:
    n = n / 2
  # If after dividing by two the number is 1, it's a power of two
  if n == 1:
    return True
  return False
  

print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False

我可以找到带有循环(除 while 之外)以及使用数学函数时的示例,但我在没有循环的情况下不知所措 这些选项中的任何一个。

python-3.x while-loop
3个回答
2
投票

n=0
是自
0 % 0 == 0
以来的一个特例。这就是为什么你有一个无限循环。

您还可以使用

return
 来简化您的 
return n == 1

语句

功能:

def is_power_of_two(n): 
    if n  == 0: 
        return False 

    while n % 2 == 0: 
        n = n / 2 

    return n == 1 

测试:

print(is_power_of_two(0)) # Should be False 
print(is_power_of_two(1)) # Should be True 
print(is_power_of_two(8)) # Should be True 
print(is_power_of_two(9)) # Should be False                                                   
print(is_power_of_two(8.1)) # Should be False

输出:

False
True
True
False
False

0
投票
def is_power_of_two(n):
  # Check if the number can be divided by two without a remainder
  # special cases: 0, because 0 % 2 = 0
  # you can either use the n > 0 extra test below
  # if n == 0: return False # or an explicit test for zero
  while (n > 0) and (n % 2 == 0): n = n / 2
  # If after dividing by two the number is 1, it's a power of two
  return n == 1

在线示例


0
投票

您可以使用“break”退出无限循环。

    def is_power_of_two(n):
  # Check if the number can be divided by two without a remainder
  while n % 2 == 0:
    if(n==0): break
    n = n / 2
  # If after dividing by two the number is 1, it's a power of two
  if n == 1:
    return True
  return False
© www.soinside.com 2019 - 2024. All rights reserved.