Home » programming » Floating mistakes

Floating mistakes

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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: