在 python 中制作 GCF 计算器

Making a GCF calculator in python

我正在 python 中制作一个计算器,它接受两个数字和 returns 它的最大公因数。当我创建一个 returns 两个因子列表的相同数字的函数时,即使我声明

我也会不断收到 'index' 错误
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)

我该怎么做才能解决这个问题?

我认为您需要检查列表长度是否足以包含您的索引,而不是检查列表长度是否为 0。

您可以使用 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

没有模块还有更简单的方法(我只是用时间补充)

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()