【问题标题】:Python GCD program [closed]Python GCD程序[关闭]
【发布时间】:2021-01-26 12:52:36
【问题描述】:
def gcd(m,n):
    
   fm = []
   for i in range(1, m+1):
       if (m%i) == 0 :
           fm.append(i)
           
   fn = []
   for j in range(1, n+1):
       if (n%j) == 0 :
           fm.append(j)
           
   cf = []
   for f in fm:
       if f in fn:
           cf.append(f)
           
   return(cf[-1])
   
print(gcd(56,23))

虽然还有其他方法可以使用 while 循环和 math.gcd 命令找到 gcd,但我的导师希望这个解决方案能够像他的编程书中提到的那样工作。如何解决 IndexError: list index out of range in the above program.

【问题讨论】:

  • 也许在尝试访问之前检查 cf 是否有任何元素? return cf[-1] if cf else None
  • 开始调试程序。发布您的发现。

标签: python python-3.x list algorithm python-2.7


【解决方案1】:

您不会在 cf. 中附加任何内容。

在第二个 for 循环中,将 fm.append(j) 更改为 fn.append(j)

【讨论】:

  • 谢谢你的错字:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
相关资源
最近更新 更多