0

I have a script which needs to be compatible with both Python 2 and 3. The code utilizes a dictionary with is generated using the following line of code:

x = {2**x-1: 1-1/8*x if x>0 else -1 for x in range(0,9)}

In Python 3.6.8, the dictionary is:

>>> x
{0: -1, 1: 0.875, 3: 0.75, 7: 0.625, 15: 0.5, 31: 0.375, 63: 0.25, 127: 0.125, 255: 0.0}

In Python 2.7.5, the dictionary is:

>>> x
{0: -1, 1: 1, 3: 1, 7: 1, 15: 1, 31: 1, 63: 1, 127: 1, 255: 1}

The dictionary generated in Python3 is the desired output. To generate the correct dictionary values in Python2, I have tried

float(1-1/8*x)
1-float(1/8*x)
1-1/8*float(x)

without success. I would greatly appreciate insight into why this behavior occurs. Thank you very much.

Alex
  • 47
  • 5
  • In Python 3, the `/` operator always does float division, and `//` does int division. In Python 2 you get different behavior depending on the types of the operands. If you explicitly convert one of the `/` operands to `float` you'll get the desired behavior in Python 2. – Samwise Nov 27 '22 at 20:14

1 Answers1

1

The solution I found that is compatible for both versions of Python is:

x = {2**x-1: 1-float(x)/8 if x>0 else -1 for x in range(0,9)}
Alex
  • 47
  • 5
  • 1
    `1-x/8.0` should also work. (IMO this isn't really an answer, since the question is *why* this behavior occurs, not how to work around it.) – Samwise Nov 27 '22 at 20:16