How do I simplify this Python for loop?

67 Views Asked by At

I'm relatively new to Python and I was wondering how I could simplify the following code any further. The code determines whether a number, n, is a power of 2 by using a for loop.

def is_power(n):
    if n <= 2:
        return True
    for i in range(3, n):
        if i * i == n:
            return True
    return False
2

There are 2 best solutions below

0
ndogac On

Here is an oversimplification :)

def is_power_of_two(n):
    return n and not (n & (n - 1))
0
Sebastien D On

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