【问题标题】:Making a GCF calculator in python用python制作一个GCF计算器
【发布时间】:2015-09-09 13:06:06
【问题描述】:

我正在用 python 制作一个计算器,它接受两个数字并返回它的最大公因数。当我创建一个返回相同数量的两个因子列表的函数时,即使我声明了,我也会不断收到“索引”错误

if len(one) == 0 and len(two) == 0:

这是我的代码:

def work(one, two):
        for i in range(len(one)):
            for j in range(len(two)):
                if len(one) != 0 and len(two) != 0:
                    if one[i] == two[j]:
                        one.pop(i)
                        two.pop(j)
                        if len(one) == 0 or len(two) == 0:
                            break
                        else:
                            work(primeF, primeF2)
            break
work(primeF, primeF2)

我能做些什么来解决这个问题?

【问题讨论】:

  • 这到底是想做什么?你永远不会返回任何东西。 work 的参数是列表还是数字? primeFprimeF2 是什么? gcf 涉及可除性,但您只检查相等性。
  • 这只是代码的一部分,我正在尝试处理列表,而不是数字。
  • 那你需要发一个minimal reproducible example。 “primeFprimeF2 是什么?它们是因子列表吗?主要因子列表?还是您对已接受的答案感到满意?

标签: python math calculator


【解决方案1】:

您可以通过使用 Python 标准库中已有的内容来大大简化您的代码:

>>> import fractions
>>> work = fractions.gcd
>>> work(12345, 67890)
15

fractions.gcd 函数应该完全符合您的要求,无需更多代码。这是模块源代码的函数副本:

def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    while b:
        a, b = b, a%b
    return a

【讨论】:

  • 我使用了一个名为 codeskulptor 的在线编辑器,但我没有实现该模块
【解决方案2】:

我认为与其检查列表长度是否为 0,不如检查列表是否足够长以包含您的索引。

【讨论】:

    【解决方案3】:

    有一种更简单的方法可以不用模块(我只是用时间来补充)

    import time
    
    def gcf (num1, num2): #The Actual Calculator
        if num1 > num2:
            num1, num2 = num2, num1
    
        for x in range (num1, 0, -1):
            if num1 % x == 0 and num2 % x == 0:
                return x
    
    
    def run(): #This section is defined so that it can be run multiple times       
        num1 = int(input("First Number: "))  #First number
        num2 = int(input("Second Number: ")) #Second number
    
        print (str (gcf (num1, num2)))
    
        run_again = input("Run again? y or yes for yes: ")
    
        if run_again == "yes" or run_again == "Y" or run_again == "Yes" or 
        run_again == "y": 
            run()
        elif run_again == "hello":
            print("hi")
            run()
        else:
            print("Goodbye!")
            time.sleep(1.5)
            quit()
    
    #Runs the code
    run()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 2018-01-05
      • 2019-05-11
      • 2016-01-28
      • 1970-01-01
      相关资源
      最近更新 更多