'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?



Solution 1:[1]

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.

Solution 2:[2]

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

conda install -c conda-forge networkx=2.5

Solution 3:[3]

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.

Solution 4:[4]

if you want always at least the networkx version that works do:

conda install -y networkx">=2.5"

sometimes adding the -c conda-forge is useful...

Solution 5:[5]

Following will install the latest version of networkx:

conda install -c anaconda networkx

Solution 6:[6]

In Windows: cmd as administrator

pip unistall networkx
pip install networkx

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lllrnr101
Solution 2 Savrige
Solution 3
Solution 4 Charlie Parker
Solution 5 Keivan
Solution 6 Rusiru Malik