Reputation: 21
Learning about functions in python3. A course question was to define a function using a while loop (and without using the math function) that determines if a parameter is a power of 2. If it is, return True. If it is not, return False. Here is the starting code:
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
I can find examples with loops (other than while) and when using the math function, but am at a loss without either of those options.
Upvotes: 1
Views: 3107
Reputation: 1
You can use break
to exit the infinite loop:
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 2 the number is 1, it's a power of two
if n == 1:
return True
return False
Upvotes: 0
Reputation: 8325
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
Upvotes: 0
Reputation: 3542
n=0
is a special case since 0 % 0 == 0
. That's why you had an infinite loop.
You can also simplify your return
statement by using return n == 1
The function:
def is_power_of_two(n):
if n == 0:
return False
while n % 2 == 0:
n = n / 2
return n == 1
tests:
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
output:
False
True
True
False
False
Upvotes: 2