Can you see the difference in Python 2 and Python 3 in the following code?

from math import log
def test():
a = 926941184
b = 737498881
print(a/b)
print(log(a/b, 2))

It is the division operator. In Python 2, the result of the division is 1, therefore the log of the result is 0 while in Python 3 we get a floating number. Keeping that in mind, spot the mistake in the following code. We want to compute whether every number in the iterable A is can be obtained by any element in A by multiplying or dividing by 2. We assume that the given numbers are positive.

from math import log
def isPowerOfTwo(num):
return int(log(num, 2)) == log(num, 2)
def getAnswer(A):
max_el = max(A)
for x in A:
if not isPowerOfTwo(max_el / x):
return "NO"
return "YES"

The code above is correct for Python 3 but not for Python 2.

from __future__ import division

That fixes the issue.

Of course, there are better ways to check whether a number is a power of two (assuming that it is an integer).

def isPowerOfTwo(num):
return num & (num - 1) == 0

### Like this:

Like Loading...

*Related*