Here is my code:

def gcd(a,b):
    if a%b == 0:
        return b
        print b

    elif b%a == 0:
        return a
        print a
    else:
        if a > b:
            gcd(a%b,b)
        elif b > a:
            gcd(b%a,a)
        else:
            return a
            print a
def lcm(a,b):
    if a==b:
        return a
    else:
        y = gcd(a,b)
        return (a*b)/y
        print (a*b)/y

What am I doing wrong? I keep getting an error because apparently y = gcd(a,b) is a NoneType and it must be an integer. But from what I see it is an integer.

有帮助吗?

解决方案

Put return in front of your recursive calls to gcd. Otherwise it returns None if it ends up in one of those branches.

The print statements after your returns are never reached.

其他提示

Actually, the code can be much simpler for gcd and lcm, since some of your base cases overlap.

def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)

def lcm(a, b):
    return a * b / gcd(a, b)

Don't forget: for recursive functions, you have to use return to link recursive calls.

once a return statement is executed , the control exits from the function call. So your print statements are never executed . You should write print statement before return . Also doing a dry run with pen and paper would help the flow of execution.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top