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?


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

conda install -c conda-forge networkx=2.5

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.

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.

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...

Following will install the latest version of networkx:

conda install -c anaconda networkx

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

  • 在 Python 中使用分数(Using Fractions in Python)
    问题 我在这里使用类来输入一个分数(当给定分子和分母时),以及将两个分数相加和相乘。 出于某种原因,导入的分数模块只能在部分程序中正常工作; gcd 方法有效,但 Fraction 方法(当给定两个数字时,放入分数格式)不起作用,而是抛出 NameError (具体来说,“全局名称 'Fractions' 未定义”)。 我究竟做错了什么? 我对 Python 比较陌生,如果有关于如何使此代码更紧凑但有更多异常的任何建议,我们将不胜感激。 这是我的代码: import fractions class FractionClass: # Initialize starting numerator and denominator. n = 0 d = 0 def __init__(self, numerator, denominator): self.n = numerator self.d = denominator # Function that adds fractions, whichs throws NameError if gcd() doesn't work! def add_fractions(self, other): try: sum_numerator = self.n + other.n sum_denominator = fractions.gcd(self.d
  • 如何将浮点数转换为分数?(How to convert float to fraction?)
    问题 这是一个家庭作业问题。 我想编写一个函数将浮点数转换为一对整数:分子和分母。 例如: float 0.5 应转换为 (1,2)。 我正在努力。 (见下文)但坦率地说,它对我来说看起来不太好。 // f is the input float int n = 1 while(fractional_part(f) > 0) f *= 10; n++ int m = f; gcd = gcd(m, n) return (m/gcd, n/gcd) 您如何将浮点数转换为分数? 回答1 你可以只使用 Fraction 库。 但是,如果您想开发算法,这里有一个建议: from math import floor from fractions import gcd def func(v, tol=1e-4): """ Don't handle negative values. Use binary search to find the fraction of a float. The algorithm is based in a very simple theorem: If a < b then a < (a+b)/2 < b. """ f = v - floor(v) lo = (0, 1) hi = (1, 1) while True: # mid = (lo + hi)/2 #
  • numpy gcd功能(Numpy gcd function)
    问题 numpy的模块结构中是否有gcd函数? 我知道fractions.gcd但认为numpy等效项可能更快,并且可以与numpy数据类型一起更好地工作。 _gcd链接外,我一直无法在Google上发现任何东西,这似乎已经过时,而且我不知道我将如何访问它暗示存在的_gcd函数。 天真地尝试: np.gcd np.euclid 没为我工作... 回答1 您可以自己编写: def numpy_gcd(a, b): a, b = np.broadcast_arrays(a, b) a = a.copy() b = b.copy() pos = np.nonzero(b)[0] while len(pos) > 0: b2 = b[pos] a[pos], b[pos] = b2, a[pos] % b2 pos = pos[b[pos]!=0] return a 这是测试结果和速度的代码: In [181]: n = 2000 a = np.random.randint(100, 1000, n) b = np.random.randint(1, 100, n) al = a.tolist() bl = b.tolist() cl = zip(al, bl) from fractions import gcd g1 = numpy_gcd(a, b) g2 = [gcd(x, y)
  • NumPy multiplying int with float seems to not work
    I am working on Google's "Doomsday Fuel" problem in Python 2.7 (it needs to be done in Python 2.7, hence the from __future__ import division line) that uses NumPy, which admittedly I am not too familiar with. The WIP code (with a lot of comments added for your convenience): from __future__ import division from fractions import Fraction import numpy as np from numpy import linalg as LA def gcd(m,n): ''' function for finding the greatest common divisor of m and n used mostly for the LCM function ''' if m < n: return gcd(n,m) return gcd(n,m%n) def lcm(m,n): ''' function for finding the least
  • NumPy 将 int 与 float 相乘似乎不起作用(NumPy multiplying int with float seems to not work)
    问题 我正在使用 NumPy 在 Python 2.7 中处理 Google 的“Doomsday Fuel”问题(它需要在 Python 2.7 中完成,因此from __future__ import division线),诚然我不太熟悉。 WIP 代码(为方便起见添加了很多注释): from __future__ import division from fractions import Fraction import numpy as np from numpy import linalg as LA def gcd(m,n): ''' function for finding the greatest common divisor of m and n used mostly for the LCM function ''' if m < n: return gcd(n,m) return gcd(n,m%n) def lcm(m,n): ''' function for finding the least common multiple of m and n using the fact that m*n = gcd(m,n)*lcm(m,n) ''' return (m*n)/(gcd(m,n)) def answer(m): ''' m is an square
  • python如何表示分数
    python如何表示分数 Fraction函数是python中实现分数的一个模块(module),可以被拿来直接使用的代码程序,包括类、函数以及标签的定义,是python标准函数库的一部分。 使用是必须先插入模块。 from fractions import Fraction #插入模块 f =Fraction(1,2) #创建Fraction 类,并初始化为1/2 print(f ) #输出分数类对象Fraction(1, 2) 输入分数时,Fraction开头字母必须大写,否则会报错。 Fraction(2,8)+1+1.52.75运算中如果出现float数据类型,最终的结果将是float类型数据。如果运算式中只有integer类型和fraction类型,输出结果将是fraction类型。>>> >>> Fraction(2,8)+Fraction(2,5)+3 #输出:Fraction(73, 20) Fraction()方法,非常有意思,可以直接接收分数字符串变成输入。注意输入的分数要加引号。 a = Fraction(‘1/5’) print(a) #输出:Fraction(1, 5) 直接输入小数,Fraction方法直接把小数变成分数。 from decimal import Decimal Fraction(1.1) #输出:Fraction(11, 10)
  • Issues running OSMnx on conda
    I'm trying to get the Python package OSMnx running on my Windows10 machine. I'm still new to python so struggling with the basics. I've followed the instructions here https://osmnx.readthedocs.io/en/stable/ and have successfully created a new conda environment for it to run in. The installation seems to have gone ok. However, as soon as I try and import it, I get the following error >>> import osmnx as ox Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\.conda\envs\ox\lib\site-packages\osmnx\__init__.py", line 3, in <module> from ._api import * File "C
  • Python fractions模块 —— 分数相关函数
    这是一简单的模块,搞不懂python为什么不把它并入math模块? >>> import fractions >>> fractions.__all__ ['Fraction', 'gcd'] >>> fractions.gcd(12,18) Warning (from warnings module): File "<pyshell#2>", line 1 DeprecationWarning: fractions.gcd() is deprecated. Use math.gcd() instead. 6 >>> fractions.gcd(14,6) 2 >>> import math >>> math.gcd(14,6) 2 >>> 一共就俩,其中一个最大公约数函数gcd()还不推荐使用,用math中的gcd替代。 fractions模块中的类Fraction class Fraction(numbers.Rational) | Fraction(numerator=0, denominator=None, *, _normalize=True) | | This class implements rational numbers. | | In the two-argument form of the constructor, Fraction(8, 6) will |
  • 在python中添加两个分数(adding two fractions in python)
  • 计算Python中给定数字列表的LCM(Calculate the LCM of a list of given numbers in Python)
    问题 我写了一段代码,找出一列数字的LCM(最低公倍数),但是我的代码似乎有错误。 代码如下: def final_lcm(thelist): previous_thelist = thelist prime_thelist = list(set(thelist) - set(returns_new_thelist(previous_thelist)) factors = 1 for i in prime_thelist: factors = factors*i new_thelist = returns_new_thelist(previous_thelist) for i in range(1, 10000000000): s_empty = [] for j in new_thelist: if i % j == 0: s_empty.append(True) if len(new_thelist) == len(s_empty): initial_lcm = i break final_lcm = factor*initial_lcm return final_lcm def returns_new_thelist(ll): if 3 in ll: ll.remove(3) for i in ll: if checks_if_prime(i) == True: ll
  • 如何有效地获得一系列数字的 GCD 和 LCM?(How to get GCD and LCM of a range of numbers efficiently?)
  • 表示Java分数的最佳方法?(Best way to represent a fraction in Java?)
    问题 我正在尝试使用Java中的分数。 我想实现算术函数。 为此,我首先需要一种将功能标准化的方法。 我知道在我有一个共同的分母之前,我不能加1/6和1/2。 我将不得不添加1/6和3/6。 天真的方法会让我加2/12和6/12,然后减少。 如何以最少的性能损失获得一个共同的分母? 哪种算法最适合呢? 版本8(感谢hstoerr): 改进包括: 现在equals()方法与compareTo()方法一致 final class Fraction extends Number { private int numerator; private int denominator; public Fraction(int numerator, int denominator) { if(denominator == 0) { throw new IllegalArgumentException("denominator is zero"); } if(denominator < 0) { numerator *= -1; denominator *= -1; } this.numerator = numerator; this.denominator = denominator; } public Fraction(int numerator) { this.numerator =
  • Addition, Subtraction, Multiplication, & Division with Fractions in Java (Homework)
    I have written this code as my answer to an assignment I recieved in AP Computer Science, and my teacher is having my redo this because the answers don't work. I can only compile it on my machine, so I am relying on my teacher as to what results is produces now, which are below. This assignment is do by midnight, tonight, and the procrastinator I am waited till now to ask for help here, but still, it is VERY much appreciated. Also, it's my first time on here, so sorry that some of the code isn't formatted properly. Thanks for the help! Results ATM if a = 3/4 and b = 5/6 a.add(b) produces 35/24
  • 具有多个数字的欧几里得算法(GCD)?(Euclidean algorithm (GCD) with multiple numbers?)
    问题 因此,我正在用Python编写程序以获取任意数量的GCD。 def GCD(numbers): if numbers[-1] == 0: return numbers[0] # i'm stuck here, this is wrong for i in range(len(numbers)-1): print GCD([numbers[i+1], numbers[i] % numbers[i+1]]) print GCD(30, 40, 36) 该函数采用数字列表。 这应该打印2。但是,我不了解如何递归使用算法,因此它可以处理多个数字。 有人可以解释吗? 更新,仍然无法正常工作: def GCD(numbers): if numbers[-1] == 0: return numbers[0] gcd = 0 for i in range(len(numbers)): gcd = GCD([numbers[i+1], numbers[i] % numbers[i+1]]) gcdtemp = GCD([gcd, numbers[i+2]]) gcd = gcdtemp return gcd 好,解决了 def GCD(a, b): if b == 0: return a else: return GCD(b, a % b) 然后使用reduce,就像 reduce(GCD,
  • 在给定分子和分母的范围内,在 0..1 之间找到与给定随机实数最接近的整数分数(Finding the closest integer fraction to a given random real between 0..1, given ranges of numerator and denominator)
    问题 给定两个范围的正整数x: [1 ... n]和y: [1 ... m]和从 0 到 1 的随机实数 R,我需要从 x 和y 使得 x_i / y_j 最接近 R。 找到这对的最有效方法是什么? 回答1 使用 Farey 序列 这是一个简单且数学上漂亮的算法来解决这个问题:运行二分搜索,在每次迭代中,下一个数字由中位数公式(如下)给出。 根据法里数列的性质,该数是该区间内分母最小的数。 因此,这个序列将始终收敛,并且永远不会“错过”一个有效的解决方案。 在伪代码中: input: m, n, R a_num = 0, a_denom = 1 b_num = 1, b_denom = 1 repeat: -- interestingly c_num/c_denom is already in reduced form c_num = a_num + b_num c_denom = a_denom + b_denom -- if the numbers are too big, return the closest of a and b if c_num > n or c_denom > m then if R - a_num/a_denom < b_num/b_denom - R then return a_num, a_denom else return b_num, b
  • 将十进制数转换为javascript中的分数或最接近的分数(convert decimal number to fraction in javascript or closest fraction)
    问题 所以我希望能够将任何十进制数字转换为分数。 在两种形式中,例如一种没有余数的形式: 3/5或3/5数: 3 1/4 。 我在做什么是这个.. 可以说我有号码.3435。 计算小数点后的位数。 用数字之前的乘幂乘以10。 然后以某种方式找到最大的共同因素。 现在我不知道如何找到GCF。 而且我也不知道如何实现逻辑来找到精确地表示分数或小数形式的分数(如果不存在精确的分数)。 我到目前为止的代码:(正在测试) x = 34/35; a = x - x.toFixed(); tens = (10).pow(a.toString().length - 2); numerator = tens * x; denominator = tens; 回答1 您的前两个步骤是合理的。 但是,您应该为分子和分母计算最大公除数(GCD),然后将分子和分母除以该除数以获得所需的分数。 GCD很容易计算。 这是Euclid的算法: var gcd = function(a, b) { if (!b) return a; return gcd(b, a % b); }; 编辑 我添加了一个可以正常工作的JSFiddle。 回答2 您可以对不同的分母使用蛮力测试,并保留误差最小的结果。 下面的算法是您可能如何执行此操作的示例,但是效率低下,并且只能搜索最多10000个分母。 function find
  • 用于列表的 Python gcd(Python gcd for list)
    问题 我想计算一个数字列表的 gcd 。 但我不知道我的代码有什么问题。 A = [12, 24, 27, 30, 36] def Greatest_Common_Divisor(A): for c in A: while int(c) > 0: if int(c) > 12: c = int(c) % 12 else: return 12 % int(c) print Greatest_Common_Divisor(A) 回答1 这是我使用的一段代码: from fractions import gcd from functools import reduce def find_gcd(list): x = reduce(gcd, list) return x 回答2 从 python 3.9 开始,python 获得了对通过数字列表计算 gcd 的内置支持。 import math A = [12, 24, 27, 30, 36] print(math.gcd(*A)) 输出: 3 回答3 def gcd (a,b): if (b == 0): return a else: return gcd (b, a % b) A = [12, 24, 27, 30, 36] res = A[0] for c in A[1::]: res = gcd(res , c) print res
  • 计算分数的Java程序(Java program for calculating fractions)
    问题 该程序的目的是为一个分数获取两个用户输入,从用户那里接收一个运算符,然后再为第二个分数获取两个用户输入。 程序必须检查两个分数中使用的数字是否在 0-99 之间并且具有非零分母。 该程序还必须确保用户输入有效的运算符(-、+、*、/)。 我现在面临的唯一问题是我的变量都没有被初始化,而且我不知道如何使输出看起来像这样: 1 1 3 --- + --- = --- 4 8 8 这是我到目前为止的代码,任何帮助将不胜感激,因为我使用 java 的知识很少: import java.util.Scanner; public class FractionCalculator { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n1; int n2; int d1; int d2; int n; int d; char o; int m1,m2; int tempN1, tempN2; int lcm, x; System.out.println("Enter a numerator for fraction 1: "); n1 = in.nextInt(); System.out.println("Enter a denominator for fraction 1:
  • Using Fractions in Python
    I'm using classes here to input a fraction (when given the numerator and denominator), as well as add and multiply two fractions together. For some reason, the imported fractions module only works correctly for part of the program; the gcd method works, but the Fraction method (where when given two numbers, puts into fraction format) does not work, instead throwing a NameError (specifically, "global name 'Fractions' is not defined"). What am I doing wrong? I am relatively new to Python, and any suggestions on how to make this code tighter with more exceptions would be greatly appreciated. Here
  • python类分数(python class fraction numbers)
    问题 我制作了一个代码,让用户以“d/n”的形式输入两个分数。 我怎样才能让它打印分数的简化形式? 例如:当我输入 2/4 时,它会打印 1/2? import sys class Rational: def __init__(self,n,d): self.numerator= n self.denominator= d def value(self): return float(self.numerator)/float(self.denominator) def __repr__(self): return "%d/%d ~ %g" % (self.numerator,self.denominator,self.value()) def read(self): while 1: try: s=raw_input("Enter fraction n/d: ") n,d= s.split("/") self.numerator= int(n) self.denominator= int(d) except KeyboardInterrupt: print exit() except: print sys.exc_info()[0] print "bad input, try again." else: if int(d)==0: print "The denominator