0

Hi consider this code below:

DNA = "ACTGATCGATTACGTATAGTATTTGCTATCATACATATATATCGATGCGTTCAT"
lenght_DNA = len(DNA)
print ("lenght:" + str(lenght_DNA))
a_count = DNA.count('A')
print ("A-count:" + str(a_count))
t_count = DNA.count('T')
print ("T-count:" + str(t_count))
AT_content = (a_count + t_count)/(lenght_DNA)
print ("AT_content:" + str(AT_content))

In Python 2 the final print gives 0 in python 3 a correct decimal number like 0.63blabla. How do i get the same behavior in Python 2?

BlueStarry
  • 677
  • 1
  • 7
  • 13

3 Answers3

3

The division operator in Python 2 on two integer arguments, which your lengths are, will do integer division. In integer division the fractional part is discarded. In Python 3 this was changed to do floating point division.

There are two solutions:

The first is to cast the arguments to a float:

AT_content = float(a_count + t_count)/(lenght_DNA)

the second is to change the division behaviour to the Python 3 behaviour at the top of your script:

from __future__ import division

Luka
  • 177
  • 6
1

How do i get the same behavior in Python 2?

I would look here for that - however it's much easier (and highly recommended) to learn more broadly the 2v3 differences and understand the process rather than be told this one piece of information

Graham
  • 7,431
  • 18
  • 59
  • 84
Scott Stainton
  • 394
  • 2
  • 14
-1

You either have to define the operand as an integer value in form of this or you need to explicitly cast any operand to float:

In [1]: 2/3
Out[1]: 0

In [2]: float(2)/3
Out[2]: 0.6666666666666666

In [3]: 2/float(3)
Out[3]: 0.6666666666666666

In [5]: 2.0/3
Out[5]: 0.6666666666666666

In [6]: 2/3.0
Out[6]: 0.6666666666666666

Another way, which also gives you control over precision, rounding and others is the application of decimal package. It also gives you the same approach in either Python 2 or 3:

In [7]: from decimal import *

In [8]: Decimal(2)/Decimal(3)
Out[8]: Decimal('0.6666666666666666666666666667')

Read more here: https://docs.python.org/2/library/decimal.html

Third approach would be to import the python 3 floating point division handling from __future__ like this:

In [9]: from __future__ import division

In [10]: 2/3
Out[10]: 0.6666666666666666
ferdy
  • 7,366
  • 3
  • 35
  • 46