Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import Error: can't import name gcd from fractions

I'm trying to import a function called gcd from a module called fractions with from fractions import gcd. For some reason, PyCharm throws an ImportError:

    from fractions import gcd
ImportError: cannot import name 'gcd' from 'fractions' 

I had this working before, what am I doing wrong?

like image 548
Matthew Schell Avatar asked Feb 12 '21 15:02

Matthew Schell


3 Answers

fractions.gcd(a, b) has been moved to math.gcd(a, b) in Python 3.9.

In fact it has been deprecated in Python 3.5 already (in brackets):

Python Version fractions.gcd(a, b) math.gcd(a, b) math.gcd(*integers)
Python 3.0 X
Python 3.1 X
Python 3.2 X
Python 3.3 X
Python 3.4 X
Python 3.5 (X) X
Python 3.6 (X) X
Python 3.7 (X) X
Python 3.8 (X) X
Python 3.9 X
Python 3.10 X
Python 3.11 X

math.gcd can also take more than 2 arguments starting from 3.9, or even 0 or 1 argument.

like image 132
xjcl Avatar answered Oct 16 '22 20:10

xjcl


It's an issue with old networkx versions. Solve this updating networkx:

conda install -c conda-forge networkx=2.5
like image 40
Savrige Avatar answered Oct 16 '22 21:10

Savrige


Your traceback says Python 3.9 and the documentation says gcd is a function in math

Changed in version 3.9: The math.gcd() function is now used to normalize the numerator and denominator. math.gcd() always return a int type. Previously, the GCD type depended on numerator and denominator.

like image 6
lllrnr101 Avatar answered Oct 16 '22 22:10

lllrnr101