All of the answers are good, but fail to address the dynamic programming nature of the solution. Quote from wikipedia:
Once the solution to a given subproblem has been computed, it is stored or "memoized": the next time the same solution is needed, it is simply looked up.
So we need to do some storing. And this storage needs to persist across multiple function calls...in this way the first few calls will be time consuming, but after that we're just doing lookups.
So the first change we make is to make the results dict a global...name it in all caps as per the python style guide.
RESULTS = {} # initialize this separately, near the top of the program, outside of any functions or classes
def isPowerOfTwo(n):
global RESULTS
if n in RESULTS:
return True
Then we also want to be breaking this problem down. In the iterative, bottom-up, approach, we start low and build upwards until we reach n
, as you had. However, we start with a check to see if we have already completed this calculation. Also, I changed the first condition to if i == 1
because, technically, 1 is a power of 2.
for i in range(1, n + 1):
if i in RESULTS:
continue
if i == 1:
RESULTS[i] = True
elif i % 2 != 0:
RESULTS[i] = False
else:
RESULTS[i] = RESULTS[i/2]
return RESULTS[n]
However, it bears mentioning that this problem -- determining if a number is a power of two -- isn't particularly well-suited to dynamic programming, and, as the other answers have shown, there are faster ways of determining if a number is a power of two.
Regardless, the full code is now:
RESULTS = {} # initialize this separately, near the top of the program, outside of any functions or classes
def isPowerOfTwo(n):
global RESULTS
if n in RESULTS:
return True
for i in range(1, n + 1):
if i in RESULTS:
continue
if i == 1:
RESULTS[i] = True
elif i % 2 != 0:
RESULTS[i] = False
else:
RESULTS[i] = RESULTS[i/2]
return RESULTS[n]
snake_case
rather thancamelCase
. See PEP 8, the Python style guide. \$\endgroup\$